Open-source design agent: on-brand stills, decks, diagrams, charts and motion graphics from a chat thread, built on Deep Agents.
JavaScript agentagentsai-agentdeepagentsdesignhyperframeslanggraphmanaged-agentsmotion-graphicspaperslackvideo
Images through the gateway, issue 41, and the friction log (#42)
Amal Irgashev7c5c55b5b2b1
diff --git a/.agents/skills/brand-onboarding/SKILL.md b/.agents/skills/brand-onboarding/SKILL.mdindex 6686d3d..0a85557 100644--- a/.agents/skills/brand-onboarding/SKILL.md+++ b/.agents/skills/brand-onboarding/SKILL.md@@ -41,3 +41,9 @@ leave it out and list it as a question for the person.always renders the sample brand.8. Hand the person the open questions, including rules the guide contradicts itself on; the pack isdone when they have reviewed it.+9. Tell them to redeploy. On Managed Deep Agents the pack ships with the deployment, so Slack keeps+ the old brand until `uv run mda deploy`; local runs pick it up at once.+10. Offer a Slack app icon in the new brand:+ `uv run design-agent ask "Our Slack app icon: a 1024x1024 PNG, the logo mark centred on the brand ground, no text"`.+ The person uploads it in the Slack app's settings (Basic Information, Display Information).+ Slack has no API for an app's icon, so neither MDA nor this repo can set it for them.diff --git a/.env.example b/.env.exampleindex 935560b..309ab9a 100644--- a/.env.example+++ b/.env.example@@ -14,7 +14,7 @@ DESIGN_AGENT_MODEL_TIMEOUT_SECONDS=600 # one call's stall ceilingDESIGN_AGENT_MODEL_BASE_URL=DESIGN_AGENT_MODEL_API_KEY_ENV=ANTHROPIC_API_KEY=-OPENAI_API_KEY=+OPENAI_API_KEY= # images; without it, images go through the gateway when you use itGOOGLE_API_KEY=LANGSMITH_API_KEY= # MDA deploy/dev, LangSmith sandboxes, tracing, optional gatewayLANGSMITH_GATEWAY_API_KEY=diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a4599c..33387dd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,16 @@### Added+- Image generation goes through the LangSmith Gateway when there is no `OPENAI_API_KEY` and the+ deployment uses the gateway (a `langsmith:` model or `LANGSMITH_GATEWAY_API_KEY`); a gateway+ workspace with no OpenAI key says so.+- LangSmith's managed tool servers (Parallel web search) work locally and self-hosted with no header+ config: they are sent `LANGSMITH_API_KEY`. `config/mcp.example.toml` has the entry.+- `sandbox publish` says it takes 10-15 minutes, numbers its steps and reports the time it took.+- README: what `sandbox publish` and `mda deploy` each do, the gateway setup, agent environments and+ where their traces are, example asks, and which skills are for coding agents. The brand-onboarding+ skill reminds you to redeploy and offers a Slack app icon.+- Every run's trace names the template it came from: a `template:langchain-ai/design-agent` tagand `ls_template` / `ls_template_version` metadata, on MDA's root run and through the sharedtrace middleware everywhere else, so a renamed fork still counts. Nothing about the deployment@@ -17,6 +27,13 @@connection can belong to each person (`owner = "user"`), so MDA asks whoever has not connectedto sign in with a link and the agent then acts as them. `docs/integrations.md` sets each up.+### Fixed++- Self-hosted and local: summarization no longer fails with `permission_denied` offloading history+ and images (#41). Deep Agents' artifacts go to `/workspace/.agent/`, which the agent can write.+- Slack progress carries on as an updated message when Slack ends a long stream+ (`message_not_in_streaming_state`), instead of stopping.+### Changed- A plain `mda deploy` deploys the project, and `mda dev` runs it: vendored skills' binary filesdiff --git a/README.md b/README.mdindex 81b1d7a..75c00d6 100644--- a/README.md+++ b/README.md@@ -143,17 +143,31 @@ LangSmith Cloud) and a model key:curl -fsSL https://raw.githubusercontent.com/langchain-ai/design-agent/main/install.sh | bashcd design-agentuv run design-agent config set LANGSMITH_API_KEY=lsv2_… ANTHROPIC_API_KEY=sk-ant-…-uv run design-agent sandbox publish # once per workspace: the agent's computer-uv run mda deploy+uv run design-agent sandbox publish # once per workspace, 10-15 min: the agent's computer+uv run mda deploy # the agent itself, and its Slack app```The installer gets [uv](https://docs.astral.sh/uv/) if you don't have it, clones the repository andinstalls its dependencies; `git clone` and `uv sync` do the same.+The two last commands do different things. `sandbox publish` builds the Linux machine every thread+works on, as a snapshot in your LangSmith workspace; nothing you can talk to exists yet. `mda deploy`+deploys the agent, which clones that machine for each thread. Publish again only when+`sandbox/setup.sh` changes.++**On the LangSmith Gateway?** Skip the provider key and run+`uv run design-agent config set DESIGN_AGENT_MODEL=langsmith:anthropic/claude-opus-5-5`. The agent+then uses `LANGSMITH_GATEWAY_API_KEY`, else `LANGSMITH_API_KEY`, and image generation goes through+the gateway too when there is no `OPENAI_API_KEY`. For any other OpenAI-compatible endpoint, set+`DESIGN_AGENT_MODEL_BASE_URL` and `DESIGN_AGENT_MODEL_API_KEY_ENV` ([Models](docs/models.md)).+The first deploy sets up the agent's Slack app. Authorize it in your workspace, then mention theagent in a channel. It's how we run ours at LangChain. Try changes on a separate copy with-`uv run mda deploy --name design-agent-test`; [Deploy with MDA](docs/deploy-mda.md) covers keys,-what ships and checking it works.+`uv run mda deploy --name design-agent-test`. In a workspace with agent mode,+`uv run mda deploy --agent-environment production` (or `staging`, `development`) deploys into that+environment of the agent, and each environment keeps its own traces: open the agent in LangSmith+and pick the environment. `uv run mda dev` traces to its Local environment.+[Deploy with MDA](docs/deploy-mda.md) covers keys, what ships and checking it works.**Or ask your coding agent.** Open the repo in Claude Code, Codex or Cursor and say what you want.[AGENTS.md](AGENTS.md) routes each request to a step-by-step [skill](.agents/skills/):@@ -184,14 +198,26 @@ uv run design-agent ask "A LinkedIn card announcing our design review service, 1## Make it yours+This repo has two kinds of skills. The ones in [`.agents/skills/`](.agents/skills/) are for your+coding agent, to set up, brand, deploy and change this repo. The ones in [`skills/`](skills/) are+what Content Studio reads while it works. [Customization](docs/customization.md) covers both.+| Want | Add | Guide || --- | --- | --- |-| Your brand | `workspace/brand/` (until then, a neutral sample brand) | [brand-onboarding skill](.agents/skills/brand-onboarding/SKILL.md) |-| Generated images | `OPENAI_API_KEY` | [Models](docs/models.md) |+| Your brand | `workspace/brand/` (until then, a neutral sample brand), then redeploy | [brand-onboarding skill](.agents/skills/brand-onboarding/SKILL.md) |+| Generated images | `OPENAI_API_KEY`, or the LangSmith Gateway | [Models](docs/models.md) || Voice, music, sound effects | `ELEVENLABS_API_KEY` | [sound skill](skills/sound/SKILL.md) || The Paper canvas | `PAPER_MODE=local` with Paper Desktop, or `bridged` when deployed | [Paper](docs/partners/paper.md) || Web search, your docs, other tools | MCP servers in `config/mcp.toml` | [Customization](docs/customization.md) |+Once it's yours, ask it in Slack like you'd ask a designer:++- "A launch card for our new feature, in LinkedIn, X and Instagram sizes."+- "A Rocky-themed promo film for our launch, with music and sound effects."+- "A chart of our weekly signups from this CSV." (attach the file)+- "A YouTube thumbnail for this video."+- "Caption this webinar clip." (attach the clip)+Everything on this page uses LangChain's brand, because that's the one we run. Licensed fonts go in`private-fonts/`, which Git ignores.diff --git a/config/mcp.example.toml b/config/mcp.example.tomlindex 33e5ba8..a657713 100644--- a/config/mcp.example.toml+++ b/config/mcp.example.toml@@ -11,6 +11,13 @@# Locally and self-hosted, a server sends headers read from the host environment (`headers_env`)# instead, and per-person servers are left out. Header values never enter the sandbox.+# --- LangSmith managed tools ---------------------------------------------------------------------++# Web search (Parallel), run by LangSmith. No credentials to set: MDA authenticates it, and locally+# and self-hosted it is sent your LANGSMITH_API_KEY. Outside GCP US, use your region's API host.+# [servers.parallel]+# url = "https://api.smith.langchain.com/v1/managed-tools/servers/parallel/mcp"+# --- Hosted integrations (official MCP servers, OAuth) ------------------------------------------# Notion: pages, databases and comments (briefs, launch docs, content calendars).diff --git a/docs/customization.md b/docs/customization.mdindex 0461458..ba55e47 100644--- a/docs/customization.md+++ b/docs/customization.md@@ -21,6 +21,9 @@ reach the sandbox as deployment files (MDA) or a read-only mount (self-hosted),## Instructions and skills+Two folders hold skills. `.agents/skills/` is for coding agents working on this repo (onboarding,+brand setup, deploy, evals); `skills/` is what the agent itself reads at work.+- `instructions.md` is the always-loaded prompt: identity, how the agent works, delivery andapproval rules, how it talks. Keep it short; the budget test fails past about 8k tokens.- `skills/<name>/SKILL.md` are workflows the agent opens when a job needs them. Add one for adiff --git a/docs/deploy-mda.md b/docs/deploy-mda.mdindex da0d67e..5511529 100644--- a/docs/deploy-mda.md+++ b/docs/deploy-mda.md@@ -43,7 +43,7 @@ default-deny: the agent's host tools fetch and generate, the sandbox only render`mda deploy` forwards every key in `.env` as a deployment secret, except LangSmith's own(`LANGSMITH_API_KEY` signs the deploy and stays home). It never reads keys from your shell forthe deployment. So keep `.env` to what the deployed agent uses: the model key, and optionally-`OPENAI_API_KEY` (images), `ELEVENLABS_API_KEY` (voice and music), `DESIGN_AGENT_*` and `PAPER_*`+`OPENAI_API_KEY` (images, unless you use the LangSmith Gateway), `ELEVENLABS_API_KEY` (voice and music), `DESIGN_AGENT_*` and `PAPER_*`settings. Self-hosting keys (`SLACK_*`, `DATABASE_URL`, `DESIGN_AGENT_API_TOKENS`) don't belong inthe `.env` you deploy from.diff --git a/docs/integrations.md b/docs/integrations.mdindex 68814fb..70e249f 100644--- a/docs/integrations.md+++ b/docs/integrations.md@@ -69,6 +69,12 @@ headers_env = { Authorization = "GITHUB_MCP_AUTHORIZATION" }with `GITHUB_MCP_AUTHORIZATION="Bearer <token>"` in `.env`. Header values never reach the sandbox.+## Web search++LangSmith runs a managed web search server (Parallel). Uncomment its entry at the top of+`config/mcp.example.toml`: on MDA it needs nothing more, and locally and self-hosted it is sent your+`LANGSMITH_API_KEY` as `x-api-key`, so there is no header to set.+## Your own serverAny HTTP or SSE MCP server works the same way; `config/mcp.example.toml` ends with a template. Adiff --git a/docs/models.md b/docs/models.mdindex 91a2804..bb8ca43 100644--- a/docs/models.md+++ b/docs/models.md@@ -12,7 +12,10 @@ ANTHROPIC_API_KEY=…default; Google, Groq and Mistral are extras (`uv sync --extra google`). The LangSmith Gateway is anoptional preset (`langsmith:anthropic/claude-opus-5-5` with `LANGSMITH_GATEWAY_API_KEY`, else`LANGSMITH_API_KEY`), never required. Anthropic and OpenAI models go through the gateway's native-routes and keep every feature in the table below; other providers use its shared route. For an OpenAI-compatible endpoint, set `DESIGN_AGENT_MODEL_BASE_URL` and+routes and keep every feature in the table below; other providers use its shared route. Image+generation uses `OPENAI_API_KEY` when it is set; without it, a deployment that uses the gateway (a+`langsmith:` model or `LANGSMITH_GATEWAY_API_KEY`) generates images through the gateway's OpenAI+route, with the OpenAI key stored in that gateway workspace. For an OpenAI-compatible endpoint, set `DESIGN_AGENT_MODEL_BASE_URL` and`DESIGN_AGENT_MODEL_API_KEY_ENV` (the name of the variable that holds its key).## Rolesdiff --git a/src/design_agent/cli.py b/src/design_agent/cli.pyindex f5169c7..1285b37 100644--- a/src/design_agent/cli.py+++ b/src/design_agent/cli.py@@ -7,6 +7,7 @@ import jsonimport shutilimport subprocessimport sys+import timeimport uuidfrom pathlib import Path@@ -527,6 +528,11 @@ def sandbox_publish(fs_gib: int, yes: bool) -> None:f"This builds a {fs_gib} GiB snapshot in your LangSmith workspace (sandbox time is billed). Continue?"):sys.exit(1)+ click.echo(+ "Building the agent's computer. This takes about 10-15 minutes; leave it running. It is "+ "only the sandbox image, once per workspace: `uv run mda deploy` deploys the agent itself."+ )+ started = time.monotonic()client = SandboxClient(api_key=settings.langsmith_api_key.get_secret_value())try:published = publish(client, _root(), fs_gib=fs_gib, say=click.echo)@@ -534,7 +540,10 @@ def sandbox_publish(fs_gib: int, yes: bool) -> None:click.echo(f"Not published: {error}", err=True)sys.exit(1)declare_snapshot(_root(), published.snapshot_name)- click.echo(f"Published {published.snapshot_name}; sandbox/__init__.py now declares it.")+ minutes = round((time.monotonic() - started) / 60)+ click.echo(+ f"Published {published.snapshot_name} in {minutes} min; sandbox/__init__.py now declares it."+ )click.echo(f"Local and self-hosted LangSmith sandboxes: DESIGN_AGENT_SANDBOX_SNAPSHOT={published.snapshot_name}")diff --git a/src/design_agent/models/factory.py b/src/design_agent/models/factory.pyindex f0cfcf3..765199d 100644--- a/src/design_agent/models/factory.py+++ b/src/design_agent/models/factory.py@@ -105,7 +105,7 @@ def build_chat_model(if spec.via_gateway:upstream = spec.upstream# Never "" -> provider key: a missing gateway key must fail at the gateway, not leak.- kwargs.setdefault("api_key", _gateway_key(settings))+ kwargs.setdefault("api_key", gateway_key(settings))if upstream.provider in GATEWAY_NATIVE_ROUTES:kwargs.setdefault("base_url", GATEWAY_ORIGIN + GATEWAY_NATIVE_ROUTES[upstream.provider])native = replace(resolved, spec=upstream)@@ -176,7 +176,7 @@ def _openai(settings: Settings, resolved: ResolvedModel, kwargs: dict[str, Any])return ChatOpenAI(model=resolved.spec.model, **kwargs)-def _gateway_key(settings: Settings) -> str:+def gateway_key(settings: Settings) -> str:"""The gateway credential: its own key, else the LangSmith key; "" when there is neither."""for key in (settings.langsmith_gateway_api_key, settings.langsmith_api_key):if key is not None and key.get_secret_value():diff --git a/src/design_agent/runtime/sandbox/__init__.py b/src/design_agent/runtime/sandbox/__init__.pyindex f93c667..4dd6718 100644--- a/src/design_agent/runtime/sandbox/__init__.py+++ b/src/design_agent/runtime/sandbox/__init__.py@@ -24,6 +24,7 @@ from deepagents.backends.protocol import (from design_agent.config import Settingsfrom design_agent.middleware.workspace import BackendTarget, StagingTargetfrom design_agent.runtime.sandbox.docker import (+ ARTIFACTS_ROOT,DockerLimits,DockerSandboxBackend,DockerSandboxRunner,@@ -83,7 +84,9 @@ class SandboxBinding:def _with_skills(sandbox: BackendProtocol, project_root: Path) -> CompositeBackend:skills = ReadOnlyFilesystemBackend(root_dir=project_root / "skills", virtual_mode=True)- return CompositeBackend(default=sandbox, routes={SKILLS_ROUTE: skills})+ return CompositeBackend(+ default=sandbox, routes={SKILLS_ROUTE: skills}, artifacts_root=ARTIFACTS_ROOT+ )def docker_binding(settings: Settings, project_root: Path) -> SandboxBinding:diff --git a/src/design_agent/runtime/sandbox/docker.py b/src/design_agent/runtime/sandbox/docker.pyindex 1209243..479a264 100644--- a/src/design_agent/runtime/sandbox/docker.py+++ b/src/design_agent/runtime/sandbox/docker.py@@ -39,8 +39,17 @@ _LOGGER = logging.getLogger(__name__)AGENT_USER = "1000:1000"AGENT_HOME = "/home/node"+#: Where Deep Agents offloads conversation history, large tool results and media when it+#: summarizes. Its default is `/`, which the agent cannot write.+ARTIFACTS_ROOT = "/workspace/.agent"#: Paths the agent may write. Everything else in the container is image or staged content.-AGENT_WRITABLE = ("/workspace/projects", "/workspace/attachments", "/workspace/.renders", "/tmp")+AGENT_WRITABLE = (+ "/workspace/projects",+ "/workspace/attachments",+ "/workspace/.renders",+ ARTIFACTS_ROOT,+ "/tmp",+)#: Paths the agent may read back through the file tools.AGENT_READABLE = ("/workspace", "/tmp", "/opt/design-agent/probe")#: Directories created at container start. The first set belongs to the agent; the second is@@ -50,6 +59,7 @@ AGENT_DIRS = ("/workspace/attachments","/workspace/references","/workspace/.renders",+ ARTIFACTS_ROOT,)STAGED_DIRS = ("/workspace/skills", "/workspace/tools", "/workspace/brand", "/workspace/fonts")DEFAULT_TIMEOUT_SECONDS = 30 * 60diff --git a/src/design_agent/runtime/sandbox/publish.py b/src/design_agent/runtime/sandbox/publish.pyindex f447b05..e460de1 100644--- a/src/design_agent/runtime/sandbox/publish.py+++ b/src/design_agent/runtime/sandbox/publish.py@@ -81,7 +81,7 @@ def publish(base_name = f"design-agent-base-{sha[:12]}"base = _named(client, base_name)if base is None:- say(f"Base snapshot from {base_image(project_root)} with {fs_gib} GiB of filesystem…")+ say(f"[1/3] Base snapshot from {base_image(project_root)} with {fs_gib} GiB of filesystem…")base = client.create_snapshot(base_name, base_image(project_root), fs_gib * GIB, timeout=SNAPSHOT_TIMEOUT_SECONDS)@@ -97,7 +97,10 @@ def publish(fs_capacity_bytes=fs_gib * GIB,)try:- say("Running the recipe (installs the browser, ffmpeg, fonts and the render toolchain)…")+ say(+ "[2/3] Running the recipe (installs the browser, ffmpeg, fonts and the render "+ "toolchain; the longest step)…"+ )sandbox.write(SETUP_PATH, setup)result = sandbox.run(f"bash {SETUP_PATH}", timeout=SETUP_TIMEOUT_SECONDS)if getattr(result, "exit_code", 1) != 0:@@ -107,7 +110,7 @@ def publish(probe = sandbox.run(PROBE, timeout=600)if getattr(probe, "exit_code", 1) != 0:raise PublishError("the recipe's probe failed after setup")- say("Capturing the snapshot…")+ say("[3/3] Capturing the snapshot…")snapshot = client.capture_snapshot(builder, name, fs_capacity_bytes=fs_gib * GIB, timeout=SNAPSHOT_TIMEOUT_SECONDS)diff --git a/src/design_agent/surfaces/slack/stream.py b/src/design_agent/surfaces/slack/stream.pyindex db7da5b..d33fabb 100644--- a/src/design_agent/surfaces/slack/stream.py+++ b/src/design_agent/surfaces/slack/stream.py@@ -56,6 +56,9 @@ _FINAL = AUTH_ERRORS | {"ratelimited", "channel_not_found", "not_in_channel", "i#: Refusals about one message's fields (`missing_recipient_team_id`), not the workspace: that#: message falls back, and the next one streams again._PER_MESSAGE = ("missing_", "invalid_")+#: Slack closed this message's stream (it ends idle or long streams); the message itself remains,+#: so it carries on as an ordinary message redrawn with `chat.update`.+_STREAM_ENDED = "message_not_in_streaming_state"#: Steps a fallback message shows while it works; the native stream folds the rest away.FALLBACK_STEPS = 4_GLYPHS = {@@ -269,9 +272,19 @@ class SlackProgress:return {"recipient_user_id": user, "recipient_team_id": team} if user and team else {}async def _append(self, chunks: list[Card]) -> None:- await self._client.call(- "chat.appendStream", {"channel": self._channel, "ts": self._ts, "chunks": chunks}- )+ try:+ await self._client.call(+ "chat.appendStream", {"channel": self._channel, "ts": self._ts, "chunks": chunks}+ )+ except SlackError as error:+ if error.code != _STREAM_ENDED:+ raise+ self._ended_stream()+ await self._draw(now=True)++ def _ended_stream(self) -> None:+ self._streaming = False+ _LOGGER.info("[progress] Slack ended the stream; updating the message instead")def _stop(self, error: SlackError) -> None:self._dead = True@@ -425,12 +438,17 @@ class SlackProgress:where = {"channel": self._channel, "ts": self._ts}if not self._dead and self._ts and not delete:with contextlib.suppress(SlackError):+ if self._streaming and header and header != self._header:+ retitle: Card = {"type": "plan_update", "title": header[:TITLE_LIMIT]}+ await self._append([retitle])if self._streaming:- if header and header != self._header:- retitle: Card = {"type": "plan_update", "title": header[:TITLE_LIMIT]}- await self._append([retitle])- await self._client.call("chat.stopStream", where)- else:+ try:+ await self._client.call("chat.stopStream", where)+ except SlackError as error:+ if error.code != _STREAM_ENDED:+ raise+ self._ended_stream()+ if not self._streaming:self._header = header or self._headerself._closed = Trueawait self._draw(now=True)diff --git a/src/design_agent/tools/mcp.py b/src/design_agent/tools/mcp.pyindex f14182f..7422b6c 100644--- a/src/design_agent/tools/mcp.py+++ b/src/design_agent/tools/mcp.py@@ -34,6 +34,10 @@ owned by the deployment (`owner = "agent"`: one account everyone's requests use)connect link, before the run starts). Per-person connections exist only on MDA, so local andself-hosted runtimes leave those servers out with a warning. Nothing reaches the sandbox.+LangSmith's managed tool servers (`https://api.smith.langchain.com/v1/managed-tools/...`, such as+Parallel web search) need no credentials in the config: MDA authenticates them itself, and locally+and self-hosted they are sent the workspace's `LANGSMITH_API_KEY` as `x-api-key`.+Stdio servers (`transport = "stdio"`, a local app's own CLI) run locally and self-hosted only: MDA's`define_mcp` speaks HTTP and SSE, so they are left out of its declaration with a warning. The childprocess gets the MCP SDK's short list of safe variables (home, path, shell, user), not the host's@@ -48,7 +52,7 @@ import osimport reimport tomllibfrom collections.abc import Awaitable, Callable, Mapping, Sequence-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal@@ -65,6 +69,8 @@ if TYPE_CHECKING:_LOGGER = logging.getLogger(__name__)SERVER_NAME = re.compile(r"[a-z][a-z0-9]{0,30}")+#: LangSmith's managed tool servers, in any region (module doc).+MANAGED_TOOLS = re.compile(r"https://(?:[a-z]+\.)?api\.smith\.langchain\.com/v1/managed-tools/")Owner = Literal["agent", "user"]CONFIG = Path("config") / "mcp.toml"@@ -89,12 +95,16 @@ class McpServer:"""A stdio server's executable and arguments (`url` is empty)."""bearer: SecretStr | None = field(default=None, repr=False, compare=False)"""Sent as `Authorization: Bearer …` locally and self-hosted; MDA uses `connection` instead."""+ api_key: SecretStr | None = field(default=None, repr=False, compare=False)+ """Sent as `x-api-key` locally and self-hosted: the LangSmith key, for managed tool servers."""def headers(self, env: Mapping[str, str]) -> dict[str, str] | None:"""The headers from the host environment; None when one it names is unset."""values = {header: env.get(var, "") for header, var in self.headers_env.items()}if self.bearer is not None:values["Authorization"] = f"Bearer {self.bearer.get_secret_value()}"+ if self.api_key is not None:+ values["x-api-key"] = self.api_key.get_secret_value()return None if any(not v for v in values.values()) else values@@ -179,6 +189,12 @@ def servers_for_runtime(server.name,)servers = [server for server in servers if server.owner != "user"]+ servers = [+ replace(server, api_key=settings.langsmith_api_key)+ if MANAGED_TOOLS.match(server.url) and not server.headers_env+ else server+ for server in servers+ ]if any(s.name == SERVER for s in servers):raise McpConfigError(f"config/mcp.toml declares `{SERVER}`; Paper is configured with PAPER_MODE instead"diff --git a/src/design_agent/tools/media.py b/src/design_agent/tools/media.pyindex 19a8005..ccc0d9e 100644--- a/src/design_agent/tools/media.py+++ b/src/design_agent/tools/media.py@@ -24,6 +24,7 @@ from langchain_core.tools import BaseTool, StructuredToolfrom pydantic import JsonValuefrom design_agent.config import Settings+from design_agent.models.factory import GATEWAY_NATIVE_ROUTES, GATEWAY_ORIGIN, gateway_keyfrom design_agent.tools.files import (BackendFor,WorkspaceError,@@ -40,24 +41,50 @@ ELEVENLABS_CAP_MB = 25 # five minutes of 320 kbps mp3 is about 12 MBVOICE_ID = re.compile(r"[A-Za-z0-9]{10,40}")+@dataclass(frozen=True)+class ImageRoute:+ """Where image generation goes, with the key for it and a name for messages."""++ url: str+ key: str+ via: str+++def _secret(secret: Any) -> str | None:+ return (secret.get_secret_value() or None) if secret is not None else None+++def image_route(settings: Settings) -> ImageRoute | None:+ """OpenAI with its own key; else the LangSmith Gateway's OpenAI route when this deployment uses+ the gateway (a gateway key, or a `langsmith:` lead model), which uses its workspace's OpenAI key."""+ if openai := _secret(settings.openai_api_key):+ return ImageRoute(f"{OPENAI_BASE_URL}/images/generations", openai, "OpenAI")+ uses_gateway = bool(_secret(settings.langsmith_gateway_api_key))+ try:+ uses_gateway = uses_gateway or settings.lead_model().via_gateway+ except ValueError:+ pass+ if uses_gateway and (key := gateway_key(settings)):+ url = f"{GATEWAY_ORIGIN}{GATEWAY_NATIVE_ROUTES['openai']}/images/generations"+ return ImageRoute(url, key, "the LangSmith Gateway")+ return None++@dataclass(frozen=True)class MediaKeys:"""Provider credentials, held only by host tools."""- openai: str | None+ image: ImageRoute | Noneelevenlabs: str | Nonegroq: str | Noneimage_model: str@classmethoddef from_settings(cls, settings: Settings) -> MediaKeys:- def value(secret: Any) -> str | None:- return secret.get_secret_value() if secret is not None else None-return cls(- openai=value(settings.openai_api_key),- elevenlabs=value(settings.elevenlabs_api_key),- groq=value(settings.groq_api_key),+ image=image_route(settings),+ elevenlabs=_secret(settings.elevenlabs_api_key),+ groq=_secret(settings.groq_api_key),image_model=settings.image_model,)@@ -562,8 +589,12 @@ def build_media_tools(settings: Settings, backend_for: BackendFor) -> list[BaseTtry:path = workspace_path(sandbox_path)backend = require_backend(backend_for, runtime)- if not keys.openai:- return "image generation unavailable: no OPENAI_API_KEY configured."+ route = keys.image+ if route is None:+ return (+ "image generation unavailable: no OPENAI_API_KEY, and this deployment does not "+ "use the LangSmith Gateway."+ )body: dict[str, JsonValue] = {"model": model or keys.image_model,"prompt": prompt,@@ -580,12 +611,19 @@ def build_media_tools(settings: Settings, backend_for: BackendFor) -> list[BaseTwants_alpha = str(body.get("background", "")).strip().lower() == "transparent"async with httpx.AsyncClient(timeout=240, follow_redirects=False) as client:response = await client.post(- f"{OPENAI_BASE_URL}/images/generations",- headers={"Authorization": f"Bearer {keys.openai}"},- json=body,+ route.url, headers={"Authorization": f"Bearer {route.key}"}, json=body)if response.status_code != 200:- return f"image generation failed: OpenAI HTTP {response.status_code}{_reason(response)}"+ hint = (+ " (the gateway's workspace has no OpenAI key; add one there or set "+ "OPENAI_API_KEY)"+ if response.status_code == 424+ else ""+ )+ return (+ f"image generation failed: {route.via} HTTP {response.status_code}"+ f"{_reason(response)}{hint}"+ )items = response.json().get("data") or []written: list[str] = []reports: list[str] = []diff --git a/tests/unit/test_docker_runner.py b/tests/unit/test_docker_runner.pyindex 1ccbf55..5bfbe04 100644--- a/tests/unit/test_docker_runner.py+++ b/tests/unit/test_docker_runner.py@@ -4,11 +4,14 @@ from __future__ import annotationsimport subprocessfrom collections.abc import Sequence+from pathlib import Pathfrom typing import Anyimport pytest+from design_agent.runtime.sandbox import _with_skillsfrom design_agent.runtime.sandbox.docker import (+ ARTIFACTS_ROOT,DockerSandboxBackend,DockerSandboxRunner,SandboxUnavailableError,@@ -123,6 +126,16 @@ def test_uploads_outside_writable_folders_are_refused() -> None:assert [r.error for r in results] == ["permission_denied", None]+def test_summarization_offloads_land_where_the_agent_can_write(tmp_path: Path) -> None:+ """Deep Agents writes conversation history, large results and media under the graph backend's+ artifacts root; the default `/` failed with permission_denied (issue 41)."""+ graph = _with_skills(DockerSandboxBackend(RecordingRunner(), thread_id=lambda: "t"), tmp_path)+ assert graph.artifacts_root == ARTIFACTS_ROOT+ media = f"{ARTIFACTS_ROOT}/conversation_history/media/910208ce0b6e3c89.png"+ backend = DockerSandboxBackend(RecordingRunner(), thread_id=lambda: "t")+ assert backend.upload_files([(media, b"png")])[0].error is None++@pytest.mark.parametrize("path", ["/etc/passwd", "/workspace/../etc/shadow", "/root/.ssh/id_rsa"])def test_downloads_outside_readable_folders_are_refused(path: str) -> None:backend = DockerSandboxBackend(RecordingRunner(), thread_id=lambda: "t")diff --git a/tests/unit/test_host_tools.py b/tests/unit/test_host_tools.pyindex e4f2c2b..9300968 100644--- a/tests/unit/test_host_tools.py+++ b/tests/unit/test_host_tools.py@@ -14,7 +14,7 @@ from deepagents.backends.protocol import FileDownloadResponse, FileUploadResponsfrom design_agent.config import Settingsfrom design_agent.tools.fetch import FetchRefused, build_fetch_tool, check_url, public_address-from design_agent.tools.media import _png_alpha_report, build_media_tools+from design_agent.tools.media import _png_alpha_report, build_media_tools, image_routeclass MemoryBackend:@@ -188,3 +188,46 @@ async def test_generate_image_writes_b64_output_and_reports_alpha(assert "wrote /workspace/projects/p/lamp.png" in result and "alpha verified" in resultassert seen["body"]["model"] == "gpt-image-2.5-flare"assert seen["url"].startswith("https://api.openai.com/")+++def _settings(**values: Any) -> Settings:+ return Settings(_env_file=None, **values) # type: ignore[call-arg]+++def test_images_go_to_openai_with_its_key_else_through_the_gateway() -> None:+ direct = image_route(_settings(openai_api_key="sk-test", langsmith_gateway_api_key="lsv2-g"))+ assert direct is not None and direct.url.startswith("https://api.openai.com/")+ assert direct.key == "sk-test"++ gateway = image_route(_settings(langsmith_gateway_api_key="lsv2-g", langsmith_api_key="lsv2-l"))+ assert gateway is not None+ assert gateway.url == "https://gateway.smith.langchain.com/openai/v1/images/generations"+ assert gateway.key == "lsv2-g"++ lead = image_route(+ _settings(model="langsmith:anthropic/claude-opus-5-5", langsmith_api_key="lsv2-l")+ )+ assert lead is not None and lead.key == "lsv2-l" and lead.via == "the LangSmith Gateway"++ assert image_route(_settings(langsmith_api_key="lsv2-l")) is None+++async def test_a_gateway_without_an_openai_key_says_where_to_add_one(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def fake_post(self: httpx.AsyncClient, url: str, **kwargs: Any) -> httpx.Response:+ return httpx.Response(424, content=b"{}", request=httpx.Request("POST", url))++ monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)+ backend = MemoryBackend()+ tools = {+ t.name: t+ for t in build_media_tools(+ _settings(langsmith_gateway_api_key="lsv2-g"), lambda _rt: backend+ )+ } # type: ignore[arg-type,return-value]+ result = await tools["generate_image"].coroutine(+ prompt="a lamp", sandbox_path="/workspace/projects/p/lamp.png", runtime=None+ ) # type: ignore[misc]+ assert "LangSmith Gateway HTTP 424" in result and "no OpenAI key" in result+ assert not backend.filesdiff --git a/tests/unit/test_mcp_integrations.py b/tests/unit/test_mcp_integrations.pyindex 6cc4c0c..ba92bb3 100644--- a/tests/unit/test_mcp_integrations.py+++ b/tests/unit/test_mcp_integrations.py@@ -95,3 +95,25 @@ def test_per_person_servers_run_only_on_mda(local = servers_for_runtime(tmp_path, settings(), "local")assert [s.name for s in local] == ["docs"]assert "notion left out: per-person connections need Managed Deep Agents" in caplog.text+++def test_langsmith_managed_tools_take_the_workspace_key_off_mda(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ write_config(+ tmp_path,+ '[servers.parallel]\nurl = "https://api.smith.langchain.com/v1/managed-tools/servers/'+ 'parallel/mcp"\n',+ )+ keyed = Settings(_env_file=None, langsmith_api_key="lsv2-test") # type: ignore[call-arg]+ (local,) = servers_for_runtime(tmp_path, keyed, "local")+ assert local.headers({}) == {"x-api-key": "lsv2-test"}+ assert "lsv2-test" not in repr(local)++ (deployed,) = servers_for_runtime(tmp_path, keyed, "mda")+ assert deployed.api_key is None+ declared: dict[str, Any] = {}+ monkeypatch.setattr(+ "managed_deepagents.define_mcp", lambda **config: declared.update(config) or "declared"+ )+ assert mda_declaration([deployed]) == "declared" and "parallel" in declared["servers"]diff --git a/tests/unit/test_progress.py b/tests/unit/test_progress.pyindex 095520e..82f9412 100644--- a/tests/unit/test_progress.py+++ b/tests/unit/test_progress.py@@ -304,6 +304,35 @@ async def test_the_fallback_merges_repeats_and_shows_only_the_latest_steps() ->assert "*Done*" in closed and "Read an image" not in closed+async def test_a_stream_slack_ended_carries_on_as_an_updated_message(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """Slack ends long or idle streams (`message_not_in_streaming_state`, issue 41): the same+ message keeps showing the work through `chat.update` instead of going dark."""+ fake = FakeSlack()+ middleware = lead(fake)+ stream_min = stream_module.MIN_UPDATE_SECONDS+ stream_module.MIN_UPDATE_SECONDS = 0.0+ try:+ await middleware.abefore_agent({}, RUNTIME)+ await middleware.awrap_tool_call(call("start_task", call_id="c1"), ran)+ fake.refuse.update(+ {+ "chat.appendStream": "message_not_in_streaming_state",+ "chat.stopStream": "message_not_in_streaming_state",+ }+ )+ await middleware.awrap_tool_call(call("generate_image", call_id="c2"), ran)+ await middleware.aafter_agent(ANSWERED, RUNTIME)+ finally:+ stream_module.MIN_UPDATE_SECONDS = stream_min++ (message,) = fake.posted.values()+ assert "chat.update" in fake.methods()+ assert message.text == "Done" and not message.deleted+ assert "progress stopped" not in caplog.text++async def test_a_run_with_no_slack_thread_says_nothing() -> None:"""A schedule fire, a CLI ask or a Studio session has no thread to post in, and must not try."""fake = FakeSlack()