Skip to content

The agent that grows with you

feat(connectors): connector tools send and save local files

Siddharth Balyane1b18e2bca67
diff --git a/model_tools.py b/model_tools.py
index 8dd93efc5ea..8566c62842c 100644
--- a/model_tools.py
+++ b/model_tools.py
@@ -835,7 +835,7 @@ def _execute_tool(function_name: str, function_args: dict[str, Any], original_ar
def _dispatch(next_args: dict[str, Any]) -> Any:
from tools.connectors import dispatch_connector_call, is_connector_name
if is_connector_name(function_name):
- return dispatch_connector_call(function_name, next_args, ids.tool_call_id, ids.turn_id)
+ return dispatch_connector_call(function_name, next_args, ids.tool_call_id, ids.turn_id, ids.task_id)
return registry.dispatch(function_name, next_args, **dispatch_kwargs)
with _approval_observability(ids):
diff --git a/tests/tools/test_connector_bridge_wiring.py b/tests/tools/test_connector_bridge_wiring.py
index 6ab2dd35697..13561dc994e 100644
--- a/tests/tools/test_connector_bridge_wiring.py
+++ b/tests/tools/test_connector_bridge_wiring.py
@@ -602,6 +602,8 @@ class _RecordingTransport:
def request(self, method, url, *, headers=None, json=None, timeout=None):
self.requests.append({"method": method, "url": url, "json": json})
+ if url.endswith("/schemas"): # the file-input lookup on a schema-cache miss
+ return _FakeResponse({"schemas": {}})
call = (json or {}).get("call") or {}
return _FakeResponse(
{"result": {"connector": call.get("connector"), "tool": call.get("tool"), "data": "ok"}})
@@ -618,7 +620,7 @@ def _recording_client_factory(transport):
def _sent_tools(transport):
- return [request["json"]["call"] for request in transport.requests]
+ return [request["json"]["call"] for request in transport.requests if request["url"].endswith("/execute")]
def test_hook_rewrite_and_restored_vendor_slug_reach_the_gateway_request_body(monkeypatch):
@@ -637,7 +639,7 @@ def test_hook_rewrite_and_restored_vendor_slug_reach_the_gateway_request_body(mo
{"connector": "gmail", "tool": "GMAIL_SEND_EMAIL",
"arguments": {"to": "[email protected]", "body": "[REDACTED]"}},
]
- assert "sk-secret" not in json.dumps(transport.requests[0]["json"])
+ assert "sk-secret" not in json.dumps([request["json"] for request in transport.requests])
assert out["results"][0]["response"] == "ok" # correlation survives the rewrite
diff --git a/tests/tools/test_connector_files.py b/tests/tools/test_connector_files.py
new file mode 100644
index 00000000000..362e55478e8
--- /dev/null
+++ b/tests/tools/test_connector_files.py
@@ -0,0 +1,332 @@
+"""Connector file inputs and outputs: the model passes local paths, the agent stages them through the
+tool gateway and storage, and files a tool returns are saved under the profile's downloads folder."""
+
+import json
+from pathlib import Path
+
+import pytest
+
+from hermes_constants import CONNECTOR_DOWNLOADS_SUBDIR, get_hermes_home
+from tools.connectors.gateway import files
+from tools.connectors.gateway.bridge import connector_describe, run_remote
+from tools.connectors.gateway.client import ConnectorClient
+from tools.connectors.gateway.merge import partition_calls
+
+GATEWAY = "https://tool-gateway.test"
+UPLOAD_URL = "https://storage.test/put?X-Amz-Signature=abc"
+DOWNLOAD_URL = "https://storage.test/get?X-Amz-Signature=def"
+STAGED_KEY = "project/gmail/GMAIL_SEND_EMAIL/request/key1"
+
+# The vendor's real shape for a mail attachment: one file, or an array of files, behind a $ref.
+GMAIL_SEND = {
+ "type": "object",
+ "properties": {
+ "recipient_email": {"type": "string"},
+ "attachment": {"description": "File to attach.", "anyOf": [
+ {"$ref": "#/$defs/File"}, {"type": "array", "items": {"$ref": "#/$defs/File"}}]},
+ },
+ "$defs": {"File": {"type": "object", "file_uploadable": True, "description": "A file.",
+ "properties": {"name": {"type": "string"}, "mimetype": {"type": "string"},
+ "s3key": {"type": "string"}}}},
+}
+
+
+class Response:
+ def __init__(self, status_code, body=None, content=b""):
+ self.status_code = status_code
+ self._body = body
+ self._content = content
+ self.headers = {"x-request-id": "req-1"}
+ self.text = json.dumps(body)
+
+ def json(self):
+ return self._body
+
+ def iter_content(self, chunk_size):
+ for start in range(0, len(self._content), chunk_size):
+ yield self._content[start:start + chunk_size]
+
+ def close(self):
+ pass
+
+
+class Gateway:
+ """The tool gateway's connector routes: schemas, upload staging and single-call execute."""
+
+ def __init__(self, schema=GMAIL_SEND, data=None):
+ self.schema = schema
+ self.data = data if data is not None else {"sent": True}
+ self.requests = []
+
+ def request(self, method, url, *, headers=None, json=None, timeout=None):
+ self.requests.append({"url": url, "headers": dict(headers or {}), "json": json})
+ route = url.removeprefix(f"{GATEWAY}/v1/connectors/")
+ if route == "schemas":
+ return Response(200, {"schemas": {"GMAIL_SEND_EMAIL": {
+ "connector": "gmail", "tool": "GMAIL_SEND_EMAIL", "inputSchema": self.schema}}})
+ if route == "files/upload":
+ return Response(200, {"uploadUrl": UPLOAD_URL, "headers": {"Content-Type": json["mimetype"]},
+ "descriptor": {"name": json["filename"], "mimetype": json["mimetype"],
+ "s3key": STAGED_KEY},
+ "expiresAt": "2026-10-14T00:05:00Z"})
+ return Response(200, {"result": {"connector": "gmail", "tool": json["call"]["tool"], "data": self.data}})
+
+ def routes(self):
+ return [request["url"].removeprefix(f"{GATEWAY}/v1/connectors/") for request in self.requests]
+
+
+class Storage:
+ def __init__(self, content=b"%PDF-1.4 attachment", status=200):
+ self.content = content
+ self.status = status
+ self.requests = []
+
+ def request(self, method, url, *, headers=None, data=None, timeout=None, stream=False):
+ self.requests.append({"method": method, "url": url, "headers": dict(headers or {}), "data": data})
+ return Response(self.status, content=self.content if method == "GET" else b"")
+
+
[email protected](autouse=True)
+def _fresh_schema_cache(monkeypatch):
+ monkeypatch.setattr(files, "_FILE_INPUTS", {})
+ for name in ("HERMES_MEDIA_DELIVERY_STRICT", "TERMINAL_ENV", "TERMINAL_DOCKER_VOLUMES", "TERMINAL_CWD"):
+ monkeypatch.delenv(name, raising=False)
+
+
+def _client(gateway, storage):
+ return ConnectorClient(transport=gateway, storage=storage, endpoint_resolver=lambda: GATEWAY,
+ header_provider=lambda url: {"Authorization": "Bearer nous-token"})
+
+
+def _execute(gateway, storage, arguments, name="connectors__gmail__SEND_EMAIL"):
+ planned = partition_calls([{"name": name, "arguments": arguments}]).remote
+ (entry,) = run_remote(planned, "call-1", availability=lambda: True,
+ client_factory=lambda: _client(gateway, storage))
+ return entry
+
+
+def _pdf(path: Path, body=b"%PDF-1.4 local") -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(body)
+ return path
+
+
+def test_describe_shows_paths_and_records_both_attachment_shapes():
+ class Client:
+ def schemas(self, slugs):
+ return {"schemas": {"GMAIL_SEND_EMAIL": {"connector": "gmail", "input_schema": GMAIL_SEND}}}
+
+ leg = connector_describe(["connectors__gmail__SEND_EMAIL"], availability=lambda: True,
+ client_factory=lambda: Client())
+
+ parameters = leg.payload["tools"]["connectors__gmail__SEND_EMAIL"]["parameters"]
+ assert parameters["$defs"]["File"] == {"type": "string", "description": "A file. Pass a local file path."}
+ assert "s3key" not in json.dumps(parameters)
+ assert files._FILE_INPUTS["connectors__gmail__SEND_EMAIL"] == (("attachment",), ("attachment", "*"))
+
+
+def test_a_local_path_is_staged_put_to_storage_and_sent_as_the_descriptor(tmp_path):
+ gateway, storage = Gateway(), Storage()
+ pdf = _pdf(tmp_path / "q3.pdf")
+
+ entry = _execute(gateway, storage, {"recipient_email": "[email protected]", "attachment": str(pdf)})
+
+ assert entry["response"] == {"sent": True}
+ # One schema lookup on the cache miss, one stage, one execute; nothing else reaches the gateway.
+ assert gateway.routes() == ["schemas", "files/upload", "execute"]
+ assert gateway.requests[1]["json"] == {"toolkit": "gmail", "tool": "GMAIL_SEND_EMAIL", "filename": "q3.pdf",
+ "mimetype": "application/pdf", "size": pdf.stat().st_size}
+ assert gateway.requests[2]["json"]["call"]["arguments"]["attachment"] == {
+ "name": "q3.pdf", "mimetype": "application/pdf", "s3key": STAGED_KEY}
+ (put,) = storage.requests
+ assert (put["method"], put["url"], put["data"]) == ("PUT", UPLOAD_URL, pdf.read_bytes())
+ # Storage gets exactly the gateway's headers: never the gateway bearer.
+ assert put["headers"] == {"Content-Type": "application/pdf"}
+
+
+def test_every_path_in_an_array_input_is_staged_and_the_cache_spares_a_second_lookup(tmp_path):
+ gateway, storage = Gateway(), Storage()
+ paths = [str(_pdf(tmp_path / "a.pdf")), str(_pdf(tmp_path / "b.pdf"))]
+
+ _execute(gateway, storage, {"attachment": paths})
+ _execute(gateway, storage, {"attachment": paths[0]})
+
+ assert gateway.routes() == ["schemas", "files/upload", "files/upload", "execute", "files/upload", "execute"]
+ assert [put["data"] for put in storage.requests] == [b"%PDF-1.4 local"] * 3
+
+
[email protected](("make_path", "code"), [
+ (lambda tmp: _pdf(get_hermes_home() / ".env"), "FILE_NOT_ALLOWED"), # credential store: denied
+ (lambda tmp: tmp / "missing.pdf", "FILE_NOT_FOUND"),
+ (lambda tmp: tmp, "FILE_NOT_FOUND"), # a directory is not a regular file
+])
+def test_a_refused_path_fails_the_call_before_any_upload(tmp_path, make_path, code):
+ gateway, storage = Gateway(), Storage()
+
+ entry = _execute(gateway, storage, {"attachment": str(make_path(tmp_path))})
+
+ assert entry["error"]["code"] == code and entry["error"]["family"] == "product"
+ assert gateway.routes() == ["schemas"] and storage.requests == []
+
+
+def test_a_file_over_the_gateway_cap_is_refused_before_staging(tmp_path, monkeypatch):
+ monkeypatch.setattr(files, "CONNECTOR_FILE_MAX_BYTES", 4)
+ gateway, storage = Gateway(), Storage()
+
+ entry = _execute(gateway, storage, {"attachment": str(_pdf(tmp_path / "big.pdf"))})
+
+ assert entry["error"]["code"] == "FILE_TOO_LARGE"
+ assert "files/upload" not in gateway.routes() and storage.requests == []
+
+
+def test_a_failed_storage_put_never_executes_the_call(tmp_path):
+ gateway, storage = Gateway(), Storage(status=403)
+
+ entry = _execute(gateway, storage, {"attachment": str(_pdf(tmp_path / "q3.pdf"))})
+
+ assert entry["error"]["code"] == "FILE_UPLOAD_FAILED" and entry["error"]["family"] == "backend"
+ assert "execute" not in gateway.routes()
+ assert UPLOAD_URL not in json.dumps(entry)
+
+
+def test_a_returned_file_is_saved_and_the_model_sees_only_its_path():
+ output = {"name": "invoice.pdf", "mimetype": "application/pdf", "url": DOWNLOAD_URL,
+ "expiresAt": "2026-10-14T01:00:00Z"}
+ gateway = Gateway(data={"attachments": [output]})
+ storage = Storage(content=b"%PDF received")
+
+ entry = _execute(gateway, storage, {"message_id": "m1"})
+
+ (saved,) = entry["response"]["attachments"]
+ assert set(saved) == {"name", "mimetype", "path"}
+ path = Path(saved["path"])
+ assert path.parent == get_hermes_home() / CONNECTOR_DOWNLOADS_SUBDIR
+ assert path.name.endswith("-invoice.pdf") and path.read_bytes() == b"%PDF received"
+ assert [request["headers"] for request in storage.requests] == [{}]
+ assert "X-Amz" not in json.dumps(entry)
+
+
+def test_a_second_download_of_the_same_name_never_overwrites_the_first():
+ output = {"name": "a.pdf", "mimetype": "application/pdf", "url": DOWNLOAD_URL}
+ first = _execute(Gateway(data=output), Storage(content=b"one"), {"id": "1"})["response"]["path"]
+ second = _execute(Gateway(data=output), Storage(content=b"two"), {"id": "2"})["response"]["path"]
+
+ assert first != second
+ assert (Path(first).read_bytes(), Path(second).read_bytes()) == (b"one", b"two")
+
+
+def test_a_failed_download_keeps_the_result_and_names_the_file_error():
+ output = {"name": "a.pdf", "mimetype": "application/pdf", "url": DOWNLOAD_URL}
+ entry = _execute(Gateway(data={"file": output, "subject": "hi"}), Storage(status=404), {"id": "1"})
+
+ assert entry["response"]["subject"] == "hi"
+ assert entry["response"]["file"]["error"].startswith("download failed")
+ assert "url" not in entry["response"]["file"]
+ assert not list((get_hermes_home() / CONNECTOR_DOWNLOADS_SUBDIR).iterdir())
+
+
+def test_a_replayed_file_without_a_link_passes_through():
+ replay = {"name": "a.pdf", "mimetype": "application/pdf"}
+ storage = Storage()
+
+ entry = _execute(Gateway(data=replay), storage, {"id": "1"})
+
+ assert entry["response"] == replay and storage.requests == []
+
+
+def test_strict_mode_refuses_a_fresh_file_but_resends_a_downloaded_one(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_MEDIA_DELIVERY_STRICT", "1")
+ monkeypatch.setenv("HERMES_MEDIA_TRUST_RECENT_FILES", "0")
+ output = {"name": "invoice.pdf", "mimetype": "application/pdf", "url": DOWNLOAD_URL}
+ downloaded = _execute(Gateway(data=output), Storage(content=b"%PDF received"), {"id": "1"})["response"]["path"]
+
+ refused = _execute(Gateway(), Storage(), {"attachment": str(_pdf(tmp_path / "fresh.pdf"))})
+ gateway, storage = Gateway(), Storage()
+ resent = _execute(gateway, storage, {"attachment": downloaded})
+
+ assert refused["error"]["code"] == "FILE_NOT_ALLOWED"
+ assert resent["response"] == {"sent": True}
+ assert [put["data"] for put in storage.requests] == [b"%PDF received"]
+
+
+def test_a_search_hit_shows_paths_so_execute_needs_no_schema_lookup(tmp_path):
+ from tools.connectors.gateway.bridge import ConnectorLeg
+ from tools.connectors.search import connector_entries_by_group
+
+ hits = {"results": [{"use_case": "email a file", "tools": ["GMAIL_SEND_EMAIL"]}],
+ "schemas": {"GMAIL_SEND_EMAIL": {"connector": "gmail", "description": "Send", "input_schema": GMAIL_SEND}}}
+ (entries,), failure = connector_entries_by_group(["email a file"], connector_search=lambda q: ConnectorLeg(hits))
+ gateway, storage = Gateway(), Storage()
+
+ _execute(gateway, storage, {"attachment": str(_pdf(tmp_path / "q3.pdf"))})
+
+ assert failure is None and "s3key" not in json.dumps(entries[0].schema)
+ assert gateway.routes() == ["files/upload", "execute"]
+
+
+def test_a_relative_path_resolves_against_the_session_working_directory(tmp_path, monkeypatch):
+ workspace = tmp_path / "workspace"
+ _pdf(workspace / "q3.pdf", b"from the workspace")
+ monkeypatch.setenv("TERMINAL_CWD", str(workspace))
+ storage = Storage()
+
+ _execute(Gateway(), storage, {"attachment": "q3.pdf"})
+
+ assert [put["data"] for put in storage.requests] == [b"from the workspace"]
+
+
+def test_dispatch_resolves_a_relative_path_in_the_calling_task_s_directory(tmp_path, monkeypatch):
+ import model_tools
+ from tools.connectors.gateway import bridge, config
+ from tools.registry import invalidate_check_fn_cache
+ from tools.terminal_tool import clear_task_env_overrides, register_task_env_overrides
+
+ task_dir = tmp_path / "task"
+ _pdf(task_dir / "q3.pdf", b"from the task directory")
+ _pdf(tmp_path / "other" / "q3.pdf", b"from another directory")
+ monkeypatch.setenv("TERMINAL_CWD", str(tmp_path / "other"))
+ gateway, storage = Gateway(), Storage()
+ monkeypatch.setattr(config, "connectors_available", lambda: True)
+ monkeypatch.setattr(bridge, "connectors_available", lambda: True)
+ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: _client(gateway, storage))
+ invalidate_check_fn_cache()
+ register_task_env_overrides("task-files", {"cwd": str(task_dir)})
+ try:
+ model_tools.handle_function_call(
+ "connectors__gmail__SEND_EMAIL", {"attachment": "q3.pdf"}, task_id="task-files",
+ enabled_toolsets=["connections"], session_id="s", skip_pre_tool_call_hook=True,
+ skip_tool_request_middleware=True, skip_tool_execution_middleware=True)
+ finally:
+ clear_task_env_overrides("task-files")
+
+ assert [put["data"] for put in storage.requests] == [b"from the task directory"]
+
+
+def test_a_docker_path_is_read_through_its_volume_mount(tmp_path, monkeypatch):
+ host = tmp_path / "shared"
+ _pdf(host / "report.pdf", b"from the container mount")
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{host}:/data"]))
+ gateway, storage = Gateway(), Storage()
+
+ entry = _execute(gateway, storage, {"attachment": "/data/report.pdf"})
+
+ assert entry["response"] == {"sent": True}
+ assert gateway.requests[1]["json"]["filename"] == "report.pdf"
+ assert [put["data"] for put in storage.requests] == [b"from the container mount"]
+
+
+def test_a_remote_terminal_backend_is_refused_like_media_delivery(tmp_path, monkeypatch):
+ monkeypatch.setenv("TERMINAL_ENV", "ssh")
+ gateway, storage = Gateway(), Storage()
+
+ entry = _execute(gateway, storage, {"attachment": "/home/me/q3.pdf"})
+
+ assert entry["error"]["code"] == "FILE_NOT_ALLOWED" and "ssh" in entry["error"]["message"]
+ assert "files/upload" not in gateway.routes() and storage.requests == []
+
+
+def test_a_storage_descriptor_from_the_model_is_refused_with_a_hint():
+ entry = _execute(Gateway(), Storage(), {"attachment": {"name": "a", "mimetype": "b", "s3key": "x"}})
+
+ assert entry["error"]["code"] == "FILE_NOT_ALLOWED" and "path" in entry["error"]["hint"]
diff --git a/tools/connectors/dispatch.py b/tools/connectors/dispatch.py
index cd8ba8c2fbe..af04ad5d476 100644
--- a/tools/connectors/dispatch.py
+++ b/tools/connectors/dispatch.py
@@ -8,11 +8,12 @@ from tools.connectors.gateway.config import MAX_CALLS_PER_DISPATCH
from tools.connectors.gateway.merge import assemble_results, fill_remote_failure, partition_calls
-def dispatch_connector_call(name, arguments, tool_call_id, turn_id=None):
+def dispatch_connector_call(name, arguments, tool_call_id, turn_id=None, task_id=None):
from tools.connectors.gateway.bridge import run_remote
partition = partition_calls([{"name": name, "arguments": arguments}])
- entries = run_remote(partition.remote, tool_call_id, availability=None, client_factory=None, turn_id=turn_id)
+ entries = run_remote(partition.remote, tool_call_id, availability=None, client_factory=None, turn_id=turn_id,
+ task_id=task_id)
entry = entries[0]
return json.dumps({key: value for key, value in entry.items() if key in {"response", "error", "account"}},
ensure_ascii=False)
diff --git a/tools/connectors/gateway/bridge.py b/tools/connectors/gateway/bridge.py
index 23ca1f1d3a8..afae118bc4f 100644
--- a/tools/connectors/gateway/bridge.py
+++ b/tools/connectors/gateway/bridge.py
@@ -6,6 +6,7 @@ from typing import Any, Callable, Optional, Sequence
from tools.connectors.gateway.config import connectors_available, guest_identity_pending
from tools.connectors.gateway.errors import GatewayAuthError, GatewayUnavailable, ToolGatewayError
+from tools.connectors.gateway.files import FileInputError, model_parameters, save_outputs, stage_inputs
from tools.connectors.gateway.merge import fill_remote_failure, splice_remote_results
from tools.connectors.gateway.names import parse_connector_name, vendor_slug_candidates
from tools.managed_gateway_identity import CallRef
@@ -120,7 +121,7 @@ def connector_describe(
continue
tools[composed] = {
"description": str(schema.get("description") or ""),
- "parameters": schema.get("input_schema") or {},
+ "parameters": model_parameters(composed, schema.get("input_schema") or {}),
}
return ConnectorLeg(payload={"tools": tools})
except GatewayUnavailable:
@@ -138,6 +139,7 @@ def run_remote(
availability: Optional[Callable[[], bool]],
client_factory: Optional[Callable[[], Any]],
turn_id: Optional[str] = None,
+ task_id: Optional[str] = None,
) -> list[dict[str, Any]]:
try:
available = (availability or connectors_available)()
@@ -158,15 +160,10 @@ def run_remote(
)
for plan in planned
]
- from tools.connectors.gateway.client import return_to_args
-
try:
client = client_factory() if client_factory else _default_client_factory(
CallRef(turn_id=turn_id, tool_call_id=dispatch_id))
- # A CONNECTION_REQUIRED link minted by this call is the user's next click, so the call names
- # the surface that browser should come back to.
- remote_results = client.execute(wire_planned, **return_to_args())
- entries = splice_remote_results(planned, remote_results)
+ entries = splice_remote_results(planned, _execute_with_files(client, wire_planned, task_id))
except ToolGatewayError as exc:
logger.warning(
"Connector execute for dispatch %s failed (%s): %s",
@@ -204,8 +201,8 @@ def run_remote(
# Retry confirmed misses once without disturbing successful sibling slots.
try:
- fallback_results = client.execute(fallback_planned, **return_to_args())
- fallback_entries = splice_remote_results(fallback_planned, fallback_results)
+ fallback_entries = splice_remote_results(
+ fallback_planned, _execute_with_files(client, fallback_planned, task_id))
except ToolGatewayError as exc:
logger.warning(
"Connector execute fallback for dispatch %s failed (%s): %s",
@@ -229,3 +226,27 @@ def run_remote(
entries[slot] = fallback_entry
return entries
+
+
+def _execute_with_files(client: Any, planned: Sequence[Any], task_id: Optional[str]) -> list[dict[str, Any]]:
+ """Execute ``planned`` with every file input staged first and every returned file saved.
+
+ A call whose file input is refused or fails to stage gets that error as its result and is never
+ executed; its siblings still run."""
+ from tools.connectors.gateway.client import return_to_args
+
+ results: list[Optional[dict[str, Any]]] = [None] * len(planned)
+ runnable: list[tuple[int, Any]] = []
+ for slot, plan in enumerate(planned):
+ try:
+ runnable.append((slot, stage_inputs(client, plan, task_id=task_id)))
+ except FileInputError as exc:
+ logger.warning("Connector %s file input refused (%s): %s", plan.name, exc.code, exc)
+ results[slot] = exc.result()
+ if runnable:
+ # A CONNECTION_REQUIRED link minted by this call is the user's next click, so the call names
+ # the surface that browser should come back to.
+ remote = client.execute([plan for _, plan in runnable], **return_to_args())
+ for (slot, _), result in zip(runnable, remote or ()):
+ results[slot] = save_outputs(client, result)
+ return results
diff --git a/tools/connectors/gateway/files.py b/tools/connectors/gateway/files.py
new file mode 100644
index 00000000000..19c35134f20
--- /dev/null
+++ b/tools/connectors/gateway/files.py
@@ -0,0 +1,325 @@
+"""File inputs and outputs of connector tools.
+
+The model passes a local path wherever a tool takes a file. Before execute, each path is checked
+with the media-delivery rule (the one that guards ``MEDIA:`` attachments), staged through the tool
+gateway, and PUT to the presigned storage URL; the gateway's descriptor replaces the path. Files a
+tool returns are downloaded at once into the profile's connector downloads folder, and the model
+sees ``{name, mimetype, path}``. Storage URLs and keys never reach the model or the logs.
+"""
+
+from __future__ import annotations
+
+import logging
+import mimetypes
+import os
+import re
+import tempfile
+from dataclasses import replace as dataclass_replace
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Iterator, Mapping, Optional, Sequence
+
+from tools.connectors.gateway.errors import ToolGatewayError
+from tools.connectors.gateway.merge import PlannedCall
+from tools.connectors.gateway.names import parse_connector_name, vendor_slug_candidates
+from tools.connectors.gateway.wire import CONNECTOR_FILE_MAX_BYTES, execute_error_family
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+ "DOWNLOAD_MAX_BYTES",
+ "FileInputError",
+ "model_parameters",
+ "save_outputs",
+ "stage_inputs",
+]
+
+DOWNLOAD_MAX_BYTES = 50 * 1024 * 1024
+FILE_INPUT_NOTE = "Pass a local file path."
+# The argument-path segment that stands for every element of an array.
+_ARRAY_ITEM = "*"
+_MAX_SCHEMA_DEPTH = 32
+# Terminal backends whose files this machine can read, as media delivery reads them: the host, and
+# Docker through its mounts. The others keep the model's files on another machine.
+_HOST_READABLE_BACKENDS = frozenset({"local", "docker"})
+_UNSAFE_NAME_CHARS = re.compile(r"[\x00-\x1f\x7f<>:\"|?*\\/]")
+_MAX_NAME_CHARS = 150
+
+Path_ = tuple[str, ...]
+# Composed tool name -> argument paths that are file inputs; an empty tuple means "none".
+_FILE_INPUTS: dict[str, tuple[Path_, ...]] = {}
+
+
+class _Staged(dict):
+ """A descriptor this dispatch staged; a second file-input path over the same value leaves it alone."""
+
+
+class FileInputError(Exception):
+ """A file input refused before the call reached execute; nothing ran."""
+
+ def __init__(self, code: str, message: str, *, hint: Optional[str] = None) -> None:
+ super().__init__(message)
+ self.code = code
+ self.hint = hint
+
+ def result(self) -> dict[str, Any]:
+ """The call's error entry, in the shape the gateway's execute errors take."""
+ error: dict[str, Any] = {"code": self.code, "message": str(self), "family": execute_error_family(self.code)}
+ if self.hint:
+ error["hint"] = self.hint
+ return {"data": None, "error": error}
+
+
+# ---------------------------------------------------------------------------
+# Schemas: what the model sees, and where the file inputs are
+# ---------------------------------------------------------------------------
+
+
+def model_parameters(name: str, input_schema: Any) -> dict[str, Any]:
+ """The tool's parameters as the model sees them (file inputs become path strings); records the
+ file-input argument paths for ``name`` so execute knows what to stage."""
+ if not isinstance(input_schema, dict):
+ return {}
+ _FILE_INPUTS[name] = tuple(dict.fromkeys(_file_paths(input_schema, input_schema, (), 0)))
+ return _as_model_schema(input_schema)
+
+
+def _as_model_schema(node: Any) -> Any:
+ if isinstance(node, list):
+ return [_as_model_schema(item) for item in node]
+ if not isinstance(node, dict):
+ return node
+ if node.get("file_uploadable") is True:
+ description = f"{node.get('description') or ''} {FILE_INPUT_NOTE}".strip()
+ return {"type": "string", "description": description}
+ return {key: _as_model_schema(value) for key, value in node.items()}
+
+
+def _file_paths(node: Any, root: dict[str, Any], path: Path_, depth: int) -> Iterator[Path_]:
+ """Argument paths of every ``file_uploadable`` subschema: properties, items, combinators, local refs."""
+ from tools.schema_sanitizer import resolve_local_schema_ref
+
+ if not isinstance(node, dict) or depth > _MAX_SCHEMA_DEPTH:
+ return
+ node = resolve_local_schema_ref(node, root)
+ if node.get("file_uploadable") is True:
+ yield path
+ return
+ for branch in ("anyOf", "oneOf", "allOf"):
+ for option in node.get(branch) or ():
+ yield from _file_paths(option, root, path, depth + 1)
+ properties = node.get("properties")
+ if isinstance(properties, dict):
+ for key, child in properties.items():
+ yield from _file_paths(child, root, (*path, key), depth + 1)
+ yield from _file_paths(node.get("items"), root, (*path, _ARRAY_ITEM), depth + 1)
+
+
+def _known_file_inputs(client: Any, plan: PlannedCall) -> tuple[Path_, ...]:
+ """The plan's file-input paths: recorded by search or describe, else fetched once."""
+ if plan.name in _FILE_INPUTS:
+ return _FILE_INPUTS[plan.name]
+ parsed = parse_connector_name(plan.name)
+ if parsed is None:
+ return ()
+ candidates = vendor_slug_candidates(parsed.connector, parsed.tool)
+ try:
+ schemas = (client.schemas(list(candidates)) or {}).get("schemas") or {}
+ except ToolGatewayError as exc:
+ logger.warning("connector %s: schema fetch for file inputs failed (%s); executing without staging",
+ plan.name, exc.code)
+ return ()
+ schema = next((schemas[slug] for slug in candidates if isinstance(schemas.get(slug), dict)), {})
+ model_parameters(plan.name, schema.get("input_schema") or {})
+ return _FILE_INPUTS[plan.name]
+
+
+# ---------------------------------------------------------------------------
+# Execute: stage every path at a file input
+# ---------------------------------------------------------------------------
+
+
+def stage_inputs(client: Any, plan: PlannedCall, *, task_id: Optional[str]) -> PlannedCall:
+ """``plan`` with each file-input path replaced by a staged descriptor for ``plan.tool``.
+
+ Raises ``FileInputError`` when a path is refused or a stage fails; nothing is executed then."""
+ if not _has_text(plan.arguments):
+ return plan
+ paths = _known_file_inputs(client, plan)
+ if not paths:
+ return plan
+ arguments = plan.arguments
+ for path in paths:
+ arguments = _substitute(arguments, path, lambda raw: _stage_one(client, plan, raw, task_id))
+ return dataclass_replace(plan, arguments=arguments)
+
+
+def _has_text(value: Any) -> bool:
+ """A file input needs a string; a call with none has nothing to stage."""
+ if isinstance(value, str):
+ return True
+ if isinstance(value, Mapping):
+ return any(_has_text(item) for item in value.values())
+ if isinstance(value, (list, tuple)):
+ return any(_has_text(item) for item in value)
+ return False
+
+
+def _substitute(value: Any, path: Sequence[str], stage) -> Any:
+ """A copy of ``value`` with the leaf at ``path`` staged; missing or non-path leaves stay as they are."""
+ if not path:
+ if isinstance(value, str):
+ return stage(value)
+ if isinstance(value, Mapping) and not isinstance(value, _Staged) and "s3key" in value:
+ raise FileInputError("FILE_NOT_ALLOWED", "File inputs take a local file path, not a storage descriptor.",
+ hint="Pass the path of the local file to send.")
+ return value
+ head, rest = path[0], path[1:]
+ if head == _ARRAY_ITEM:
+ return [_substitute(item, rest, stage) for item in value] if isinstance(value, list) else value
+ if isinstance(value, Mapping) and head in value:
+ return {**value, head: _substitute(value[head], rest, stage)}
+ return value
+
+
+def _stage_one(client: Any, plan: PlannedCall, raw: str, task_id: Optional[str]) -> dict[str, str]:
+ path = _readable_file(raw, task_id)
+ data = _read_bytes(raw, path)
+ name = Path(path).name[-255:]
+ mimetype = mimetypes.guess_type(name)[0] or "application/octet-stream"
+ try:
+ staged = client.stage_file(toolkit=plan.connector.lower(), tool=plan.tool, filename=name,
+ mimetype=mimetype, size=len(data))
+ except ToolGatewayError as exc:
+ if exc.code == "TOOL_NOT_ALLOWED":
+ raise FileInputError("TOOL_NOT_ALLOWED", str(exc)) from exc
+ raise FileInputError("FILE_UPLOAD_FAILED", f"The tool gateway could not stage {name}: {exc}") from exc
+ try:
+ client.put_file(staged["upload_url"], staged["headers"], data)
+ except ToolGatewayError as exc:
+ raise FileInputError("FILE_UPLOAD_FAILED", f"Uploading {name} to storage failed: {exc}") from exc
+ return _Staged(staged["descriptor"])
+
+
+def _readable_file(raw: str, task_id: Optional[str]) -> str:
+ """The host path of a file the model may send, by the media-delivery rule; else ``FileInputError``."""
+ from gateway.platforms.base import validate_media_delivery_path
+ from gateway.session_context import get_session_env
+
+ candidate = _backend_path(raw, task_id)
+ allowed = validate_media_delivery_path(candidate, session_key=get_session_env("HERMES_SESSION_KEY", ""))
+ if allowed:
+ return allowed
+ if not Path(candidate).is_file():
+ raise FileInputError("FILE_NOT_FOUND", f"{raw} is not a regular file on this machine.",
+ hint="Pass the path of an existing file.")
+ raise FileInputError(
+ "FILE_NOT_ALLOWED", f"{raw} may not leave this machine: the file-sending policy refuses it.",
+ hint="Files under the Hermes downloads and cache folders, or a folder listed in "
+ "gateway.media_delivery_allow_dirs, can be sent.")
+
+
+def _backend_path(raw: str, task_id: Optional[str]) -> str:
+ """``raw`` as an absolute path in the terminal backend's namespace, resolved the way the file
+ tools resolve it. Backends whose files live on another machine are refused, as ``MEDIA:`` is."""
+ from tools.file_tools_paths import _resolve_path_for_task, _terminal_env_type_for_task
+
+ task = task_id or "default"
+ backend = _terminal_env_type_for_task(task)
+ if backend not in _HOST_READABLE_BACKENDS:
+ raise FileInputError(
+ "FILE_NOT_ALLOWED", f"Files in the {backend} terminal backend are not on this machine, "
+ "so they cannot be sent as a connector file input.",
+ hint="Use a file on this machine, or switch to the local or Docker terminal backend.")
+ return str(_resolve_path_for_task(raw, task))
+
+
+def _read_bytes(raw: str, path: str) -> bytes:
+ try:
+ size = os.path.getsize(path)
+ if size > CONNECTOR_FILE_MAX_BYTES:
+ raise FileInputError("FILE_TOO_LARGE",
+ f"{raw} is {size // (1024 * 1024)} MiB; connector file inputs are limited to "
+ f"{CONNECTOR_FILE_MAX_BYTES // (1024 * 1024)} MiB.")
+ data = Path(path).read_bytes()
+ except OSError as exc:
+ raise FileInputError("FILE_NOT_FOUND", f"{raw} could not be read: {exc.strerror or exc}.") from exc
+ if not data:
+ raise FileInputError("FILE_NOT_FOUND", f"{raw} is empty.")
+ return data
+
+
+# ---------------------------------------------------------------------------
+# Results: save every returned file
+# ---------------------------------------------------------------------------
+
+
+def save_outputs(client: Any, result: Any) -> Any:
+ """A successful result with each ``{name, mimetype, url}`` replaced by ``{name, mimetype, path}``,
+ or ``{name, mimetype, error}`` when the download failed. Errors and replays pass through."""
+ if not isinstance(result, Mapping) or result.get("error") is not None or result.get("data") is None:
+ return result
+ return {**result, "data": _saved(client, result["data"])}
+
+
+def _saved(client: Any, value: Any) -> Any:
+ if isinstance(value, list):
+ return [_saved(client, item) for item in value]
+ if not isinstance(value, Mapping):
+ return value
+ if _is_file_output(value):
+ return _download(client, value)
+ return {key: _saved(client, item) for key, item in value.items()}
+
+
+def _is_file_output(value: Mapping[str, Any]) -> bool:
+ return all(isinstance(value.get(key), str) for key in ("name", "mimetype", "url")) and \
+ value["url"].startswith(("https://", "http://"))
+
+
+def _download(client: Any, file: Mapping[str, Any]) -> dict[str, Any]:
+ kept = {key: item for key, item in file.items() if key not in ("url", "expiresAt")}
+ try:
+ kept["path"] = _fetch_to_downloads(client, file["url"], file["name"])
+ except (ToolGatewayError, OSError) as exc:
+ logger.warning("connector file download of %s failed: %s", _safe_name(file["name"]), type(exc).__name__)
+ kept["error"] = f"download failed: {exc}"
+ return kept
+
+
+def _fetch_to_downloads(client: Any, url: str, name: str) -> str:
+ """Stream ``url`` into a temp file, then link it under a fresh name: a cut download never leaves
+ a partial file under the final name, and an existing file is never replaced."""
+ from hermes_constants import CONNECTOR_DOWNLOADS_SUBDIR, get_hermes_home, mkdir_under_hermes_home
+
+ folder = mkdir_under_hermes_home(get_hermes_home() / CONNECTOR_DOWNLOADS_SUBDIR)
+ handle = tempfile.NamedTemporaryFile(dir=folder, prefix=".partial-", delete=False)
+ try:
+ with handle:
+ client.get_file(url, handle.write, max_bytes=DOWNLOAD_MAX_BYTES)
+ target = _reserve_name(folder, _safe_name(name))
+ os.replace(handle.name, target)
+ return str(target)
+ finally:
+ Path(handle.name).unlink(missing_ok=True)
+
+
+def _reserve_name(folder: Path, name: str) -> Path:
+ """Create an empty file under a fresh ``<UTC stamp>-<name>``; the download then replaces it."""
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
+ stem, suffix = os.path.splitext(name)
+ for attempt in range(1000):
+ target = folder / (f"{stamp}-{name}" if attempt == 0 else f"{stamp}-{stem}-{attempt}{suffix}")
+ try:
+ target.open("xb").close()
+ except FileExistsError:
+ continue
+ return target
+ raise FileExistsError(f"no free name for {name}")
+
+
+def _safe_name(name: str) -> str:
+ """A basename safe on every OS: no separators, control characters, or ``.``/``..``."""
+ base = re.split(r"[\\/]", name)[-1]
+ cleaned = _UNSAFE_NAME_CHARS.sub("_", base).strip().strip(".")
+ return cleaned[-_MAX_NAME_CHARS:] or "file"
diff --git a/tools/connectors/search.py b/tools/connectors/search.py
index 2e49c78c858..7844a85314c 100644
--- a/tools/connectors/search.py
+++ b/tools/connectors/search.py
@@ -40,8 +40,9 @@ def connectors_unavailable(failure: str, *, verb: str,
def _connector_entry(name: str, connector: str, slug: str, schema: dict[str, Any]) -> CatalogEntry:
description = str(schema.get("description") or "")
- input_schema = schema.get("input_schema")
- parameters = input_schema if isinstance(input_schema, dict) else {}
+ from tools.connectors.gateway.files import model_parameters
+
+ parameters = model_parameters(name, schema.get("input_schema"))
tool_def = {"type": "function", "function": {
"name": name, "description": description, "parameters": parameters}}
text = f"{connector} {slug.replace('_', ' ')} {description}"