Skip to content

The agent that grows with you

refactor(tools): remove expired BFL FLUX 3 promo core tools (migration v39); FLUX 3 stays via video_gen/FAL for subscribers (#94599)

Teknium76e306c45843
diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.py
index e4afbbba822..ff30ee516c6 100644
--- a/agent/tool_guardrails.py
+++ b/agent/tool_guardrails.py
@@ -68,7 +68,6 @@ MUTATING_TOOL_NAMES = frozenset(
STALL_GUARD_REPEATABLE_TOOLS = frozenset(
{
"process",
- "bfl_flux3_get_result",
}
)
diff --git a/apps/desktop/src/app/artifacts/artifact-utils.ts b/apps/desktop/src/app/artifacts/artifact-utils.ts
index c0af68ccabb..0d679936adf 100644
--- a/apps/desktop/src/app/artifacts/artifact-utils.ts
+++ b/apps/desktop/src/app/artifacts/artifact-utils.ts
@@ -311,6 +311,9 @@ function toolName(message: SessionMessage): string {
}
function isArtifactProducerTool(name: string): boolean {
+ // `bfl_flux3_*` tools were removed from the core toolset, but sessions
+ // recorded while they existed still carry their tool messages — keep
+ // matching so those artifacts stay visible in history.
return ARTIFACT_PRODUCER_TOOL_RE.test(name) || name.startsWith('bfl_flux3_')
}
diff --git a/gateway/run.py b/gateway/run.py
index 9b6e0b406a5..461d75b1164 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1752,7 +1752,6 @@ _AUTO_APPEND_MEDIA_TOOL_NAMES = {
"text_to_speech",
"text_to_speech_tool",
"image_generate",
- "bfl_flux3_get_result",
}
# ---- helpers: detect interrupted tool tails & auto-continue noise ----------
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 905d5e5be03..cae665f25b4 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -3762,7 +3762,7 @@ DEFAULT_CONFIG = {
},
# Config schema version - bump this when adding new required fields
- "_config_version": 38,
+ "_config_version": 39,
}
# Optional environment variables that enhance functionality
diff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.py
index 4f8c8274773..3357aaec16b 100644
--- a/hermes_cli/config_migrations.py
+++ b/hermes_cli/config_migrations.py
@@ -827,6 +827,42 @@ def _migrate_to_38(results: Dict[str, Any], quiet: bool) -> None:
print(f" ⚠ {message}")
+def _migrate_to_39(results: Dict[str, Any], quiet: bool) -> None:
+ # ── Version 38 → 39: remove the retired `bfl` toolset from saved lists ──
+ # The six bfl_flux3_* core tools shipped for a free FLUX 3 promotional
+ # period that has since ended server-side, leaving every Nous-signed-in
+ # install paying ~2.7K tokens of schema per API call for tools that can
+ # only refuse. They were removed in favor of the standard video_gen
+ # provider surface (`video_generate`, `hermes tools` → Video Generation).
+ # Strip the toolset key wherever the auto-backfill or a picker save wrote
+ # it, so stale config can't resurrect an unknown toolset.
+ _c = _cfg()
+ read_raw_config = _c.read_raw_config
+ _persist_migration = _c._persist_migration
+
+ config = read_raw_config()
+ changed = False
+ for section in ("platform_toolsets", "known_builtin_toolsets"):
+ mapping = config.get(section)
+ if not isinstance(mapping, dict):
+ continue
+ for platform, toolsets in mapping.items():
+ if isinstance(toolsets, list) and "bfl" in toolsets:
+ mapping[platform] = [ts for ts in toolsets if ts != "bfl"]
+ changed = True
+ if changed:
+ config[section] = mapping
+ if changed:
+ _persist_migration(config)
+ results["config_added"].append("removed retired 'bfl' toolset from saved toolset lists")
+ if not quiet:
+ print(
+ " ✓ Removed the retired BFL FLUX 3 toolset from saved toolset "
+ "lists — video generation now lives under `hermes tools` → "
+ "Video Generation (Nous Subscription or FAL)."
+ )
+
+
#: Registry of (target_version, migration_fn), strictly ascending. The driver
#: applies every entry whose target version is greater than the on-disk
#: observe earlier steps' writes via read_raw_config() (filesystem state).
@@ -853,6 +889,7 @@ MIGRATIONS: Tuple[Tuple[int, Callable[[Dict[str, Any], bool], None]], ...] = (
(36, _migrate_to_36),
(37, _migrate_to_37),
(38, _migrate_to_38),
+ (39, _migrate_to_39),
)
diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.py
index a28fc09f3d8..46feaf6b740 100644
--- a/hermes_cli/tools_config.py
+++ b/hermes_cli/tools_config.py
@@ -103,7 +103,6 @@ CONFIGURABLE_TOOLSETS = [
("video", "🎬 Video Analysis", "video_analyze (requires video-capable model)"),
("image_gen", "🎨 Image Generation", "image_generate"),
("video_gen", "🎬 Video Generation", "video_generate (text/image/reference)"),
- ("bfl", "🎬 BFL FLUX 3 Video", "bfl_flux3_*"),
("x_search", "🐦 X (Twitter) Search", "x_search (requires xAI OAuth or XAI_API_KEY)"),
("tts", "🔊 Text-to-Speech", "text_to_speech"),
("stt", "🎙️ Speech-to-Text", "voice transcription (gateway voice messages + voice mode)"),
@@ -2357,12 +2356,11 @@ def _exempt_explicit_platform_native(
#: Landing late — or leaving an entry here for a second release — converts a
#: back-fill into a stuck checkbox.
#:
-#: Not gated on a Nous sign-in here: the six ``bfl_flux3_*`` tools carry
-#: ``check_fn=check_bfl_requirements``, so an enabled toolset still ships zero
-#: schemas to a user with no Nous credential — the same split Home Assistant
-#: uses. Probing the portal from this path would put a network call on every
-#: CLI start, gateway session and cron tick.
-_RECENTLY_SHIPPED_TOOLSETS = frozenset({"bfl"})
+#: A ``check_fn``-gated toolset costs nothing here for users who cannot call
+#: it: an enabled toolset still ships zero schemas when its check fails — the
+#: same split Home Assistant uses. Probing a remote service from this path
+#: would put a network call on every CLI start, gateway session and cron tick.
+_RECENTLY_SHIPPED_TOOLSETS: frozenset = frozenset()
def _enable_recently_shipped_toolsets(
diff --git a/tests/agent/test_stall_guards.py b/tests/agent/test_stall_guards.py
index 4ff12fe56e3..b79ba55c5b3 100644
--- a/tests/agent/test_stall_guards.py
+++ b/tests/agent/test_stall_guards.py
@@ -92,7 +92,7 @@ def test_arg_canonicalization_ignores_key_order():
def test_allowlisted_pollers_never_fire():
c = ToolCallGuardrailController()
- for tool in ("process", "bfl_flux3_get_result", "vendor_get_result", "job_poll"):
+ for tool in ("process", "vendor_get_result", "job_poll"):
for _ in range(STALL_GUARD_IDENTICAL_CALL_THRESHOLD + 2):
assert c.observe_identical_call(tool, {"id": "j1"}, "Generating") is None
@@ -248,7 +248,7 @@ def test_pollers_get_stub_but_never_loop_notice():
agent = _fake_agent()
args = {"id": "job1"}
results = [
- agent._append("bfl_flux3_get_result", args, _BIG, tool_call_id=f"c{i}")
+ agent._append("vendor_get_result", args, _BIG, tool_call_id=f"c{i}")
for i in range(4)
]
assert results[0] == _BIG
diff --git a/tests/hermes_cli/test_relay_plugin_cutover.py b/tests/hermes_cli/test_relay_plugin_cutover.py
index 9bb6c7aee94..5d518b74a3d 100644
--- a/tests/hermes_cli/test_relay_plugin_cutover.py
+++ b/tests/hermes_cli/test_relay_plugin_cutover.py
@@ -36,7 +36,10 @@ def test_v38_migration_removes_only_legacy_relay_plugin_keys(tmp_path):
results = migrate_config(interactive=False, quiet=True)
raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))
- assert raw["_config_version"] == 38
+ # Behavior contract, not a snapshot: the run must land at (at least) the
+ # v38 relay-cutover step; later migrations legitimately advance the
+ # version further, and pinning the literal broke on every bump.
+ assert raw["_config_version"] >= 38
assert raw["plugins"]["enabled"] == ["keep-me"]
assert any(
"observability/nemo_relay" in warning
diff --git a/tests/hermes_cli/test_tools_config.py b/tests/hermes_cli/test_tools_config.py
index 3212eb61463..e11d6e96d70 100644
--- a/tests/hermes_cli/test_tools_config.py
+++ b/tests/hermes_cli/test_tools_config.py
@@ -1034,8 +1034,8 @@ def _saved_list_from_before(platform="cli"):
@_requires_recently_shipped
def test_saved_list_gains_toolsets_that_shipped_after_it_was_written():
- """The bug: a frozen list never gained bfl, so composite users got Nous
- Portal video generation on upgrade and picker users silently did not."""
+ """The bug: a frozen list never gained a newly shipped toolset, so
+ composite users got it on upgrade and picker users silently did not."""
on_composite = _get_platform_tools(
{"platform_toolsets": {"cli": ["hermes-cli"]}},
"cli",
diff --git a/tests/tools/test_flux3_video_tool.py b/tests/tools/test_flux3_video_tool.py
deleted file mode 100644
index 35323842a58..00000000000
--- a/tests/tools/test_flux3_video_tool.py
+++ /dev/null
@@ -1,1043 +0,0 @@
-"""Native BFL FLUX 3 tools: gating, transport, media delivery, redaction."""
-
-import asyncio
-import base64
-import json
-import time
-from contextlib import contextmanager
-from types import SimpleNamespace
-from unittest.mock import patch
-
-import pytest
-
-from tools import flux3_video_tool as flux3
-
-GATEWAY = "https://tool-gateway.example.com"
-BASE_URL = f"{GATEWAY}/api/bfl"
-UPLOAD_PATH = "/api/uploads/bfl"
-
-# The shipped pacing, read before the autouse fixture below rewrites it to
-# something the tests can spend in an instant.
-_DEFAULT_POLL_BUDGET_SECONDS = flux3._POLL_BUDGET_SECONDS
-_DEFAULT_CALL_BACKSTOP_SECONDS = flux3._CALL_BACKSTOP_SECONDS
-
-_PNG = base64.b64decode(
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
-)
-
-
[email protected](autouse=True)
-def _endpoints():
- """Every test runs as if the mount is reachable unless it says otherwise."""
- with patch.object(
- flux3,
- "managed_vendor_endpoints",
- return_value={"origin": GATEWAY, "base_url": BASE_URL, "upload_path": UPLOAD_PATH},
- ):
- yield
-
-
-class _FakeResponse:
- def __init__(self, status_code=200, payload=None, text=""):
- self.status_code = status_code
- self._payload = payload
- self.text = text or (json.dumps(payload) if payload is not None else "")
-
- def json(self):
- if self._payload is None:
- raise ValueError("no json")
- return self._payload
-
-
-class _FakeClient:
- """Captures each request a handler makes.
-
- A list of responses is served in order, with the last one repeating, so a
- poll that looks twice can be given a job that finishes between looks.
- """
-
- def __init__(self, response, sink):
- self._responses = list(response) if isinstance(response, list) else [response]
- self._sink = sink
-
- async def __aenter__(self):
- return self
-
- async def __aexit__(self, *_exc):
- return False
-
- async def request(self, method, url, headers=None, json=None):
- self._sink.append({"method": method, "url": url, "headers": headers or {}, "json": json})
- response = self._responses[min(len(self._sink) - 1, len(self._responses) - 1)]
- if isinstance(response, Exception):
- raise response
- return response
-
-
-class _FakeStream:
- """A streaming GET that yields `body` in one chunk."""
-
- def __init__(self, body, status_code=200):
- self._body = body
- self.status_code = status_code
-
- async def __aenter__(self):
- return self
-
- async def __aexit__(self, *_exc):
- return False
-
- def raise_for_status(self):
- if self.status_code >= 400:
- raise RuntimeError(f"HTTP {self.status_code}")
-
- async def aiter_bytes(self):
- yield self._body
-
-
-@contextmanager
-def _fake_download(body, status_code=200):
- """Stub the clip download; yields the list of URLs that were fetched.
-
- Patched at `create_ssrf_safe_async_client` rather than at httpx, which both
- stubs the transport and asserts the download goes through the SSRF-guarded
- client — the URL is vendor-supplied and fetched from the user's machine.
- """
- from tools import url_safety
-
- fetched = []
-
- class _Client:
- async def __aenter__(self):
- return self
-
- async def __aexit__(self, *_exc):
- return False
-
- def stream(self, _method, url):
- fetched.append(url)
- return _FakeStream(body, status_code)
-
- with patch.object(url_safety, "create_ssrf_safe_async_client", lambda **_kw: _Client()):
- yield fetched
-
-
-def _run(coro):
- return asyncio.run(coro)
-
-
-def _record_sleep(sink):
- async def _sleep(seconds):
- sink.append(seconds)
-
- return _sleep
-
-
-def _stepped_clock(look_seconds):
- """A monotonic clock on which every look appears to take `look_seconds`.
-
- The poll loop reads the clock twice per look — once before the request and
- once after — so advancing on every second read charges a look exactly that
- much budget without spending any real time. Substituted for the module's
- whole ``time`` reference rather than patching ``time.monotonic`` globally,
- which would hand the same jumping clock to the event loop underneath.
- """
- reads = {"n": 0}
-
- def _monotonic():
- value = (reads["n"] // 2) * look_seconds
- reads["n"] += 1
- return value
-
- return _monotonic
-
-
-def _call(handler, args, response, headers=None):
- """Invoke a handler with the transport stubbed; returns (parsed, requests)."""
- sink = []
- import httpx
-
- with patch.object(
- flux3,
- "managed_gateway_auth_headers",
- return_value=headers if headers is not None else {"Authorization": "Bearer nous-token"},
- ), patch.object(httpx, "AsyncClient", lambda **_kw: _FakeClient(response, sink)):
- raw = _run(handler(args))
- return json.loads(raw), sink
-
-
-class TestGating:
- def test_hidden_without_a_reachable_mount(self):
- with patch.object(flux3, "managed_vendor_endpoints", return_value=None):
- assert flux3.check_bfl_requirements() is False
-
- def test_visible_to_any_signed_in_account_whatever_its_entitlement(self):
- # Entitlement is the gateway's ruling, and it states its reason in a
- # refusal the model can act on. Deciding it here as well could only
- # hide the tools from someone the server would have served, so the
- # portal's entitlement view must not be consulted at all.
- with patch.object(flux3, "peek_nous_access_token", return_value="nous-token"), \
- patch(
- "hermes_cli.nous_account.get_nous_portal_account_info",
- side_effect=AssertionError("entitlement must not gate visibility"),
- ):
- assert flux3.check_bfl_requirements() is True
-
- def test_hidden_without_a_nous_credential(self):
- # The gateway takes a Nous bearer and nothing else, so with no token
- # every call could only ever answer "sign in" — six schemas on every
- # API call for something that cannot work.
- with patch.object(flux3, "peek_nous_access_token", return_value=None):
- assert flux3.check_bfl_requirements() is False
-
- def test_a_profile_sees_a_credential_held_at_the_global_root(self, tmp_path, monkeypatch):
- # A profile that was never logged into separately still calls the
- # gateway with the root login, because the transport's refresh path
- # reads that same global fallback. Probing only the profile's own store
- # would hide the tools from someone whose calls would have worked.
- #
- # Exercised through the real auth store rather than a stub: the
- # fallback is the whole point of the test, and it lives in
- # hermes_cli.auth, not here.
- monkeypatch.delenv("TOOL_GATEWAY_USER_TOKEN", raising=False)
- root = tmp_path / "root"
- (root / "profiles" / "work").mkdir(parents=True)
- (root / "auth.json").write_text(
- json.dumps({"version": 1, "providers": {"nous": {"access_token": "root-token"}}}),
- encoding="utf-8",
- )
- monkeypatch.setenv("HERMES_HOME", str(root / "profiles" / "work"))
-
- # The profile's own store is empty, so this passes only via the
- # global-root fallback — without which the tools would be hidden.
- assert flux3.peek_nous_access_token() is None
- assert flux3.check_bfl_requirements() is True
-
- def test_the_credential_probe_never_forces_a_token_refresh(self, monkeypatch):
- # check_fn runs on every CLI start, gateway session and cron tick, so
- # it reads a cached credential rather than sitting on a synchronous
- # OAuth refresh.
- monkeypatch.setenv("TOOL_GATEWAY_USER_TOKEN", "nous-token")
- with patch.object(flux3, "read_nous_access_token", side_effect=AssertionError("refreshed")):
- assert flux3.check_bfl_requirements() is True
-
- def test_fails_closed_when_the_credential_probe_raises(self):
- with patch.object(flux3, "peek_nous_access_token", side_effect=RuntimeError("auth store unreadable")):
- assert flux3.check_bfl_requirements() is False
-
-
-class TestSubmitTransport:
- def test_text_to_video_posts_the_mode_and_arguments(self):
- response = _FakeResponse(200, {"id": "bfl_job_1", "status": "submitted", "guidance": "Poll bfl_flux3_get_result with id=bfl_job_1"})
-
- parsed, requests = _call(
- flux3._handle_text_to_video,
- {"prompt": "a lake", "aspect_ratio": "16:9", "duration": 5},
- response,
- )
-
- assert requests[0]["method"] == "POST"
- assert requests[0]["url"] == f"{BASE_URL}/generations"
- assert requests[0]["json"] == {
- "prompt": "a lake",
- "aspect_ratio": "16:9",
- "duration": 5,
- "mode": "text_to_video",
- }
- assert requests[0]["headers"]["Authorization"] == "Bearer nous-token"
- # The gateway's guidance is the model-facing text, verbatim.
- assert parsed["result"] == "Poll bfl_flux3_get_result with id=bfl_job_1"
- assert parsed["details"]["id"] == "bfl_job_1"
-
- def test_each_generate_tool_sends_its_own_mode(self):
- for handler, args, mode in [
- (flux3._handle_text_to_video, {"prompt": "a"}, "text_to_video"),
- (flux3._handle_image_to_video, {"prompt": "a", "input_image": "https://x/a.png"}, "image_to_video"),
- (
- flux3._handle_keyframes_to_video,
- {"prompt": "a", "input_images": ["https://x/a.png"], "keyframe_indices": [0]},
- "keyframes_to_video",
- ),
- (flux3._handle_video_continuation, {"prompt": "a", "input_video": "https://x/c.mp4"}, "video_continuation"),
- ]:
- _parsed, requests = _call(handler, args, _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}))
- assert requests[0]["json"]["mode"] == mode
-
- def test_urls_pass_through_without_an_upload(self):
- # Forwarding a URL is cheaper than downloading and re-uploading it.
- _parsed, requests = _call(
- flux3._handle_image_to_video,
- {"prompt": "a", "input_image": "https://example.com/a.png"},
- _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}),
- )
- assert requests[0]["json"]["input_image"] == "https://example.com/a.png"
-
- def test_a_refusal_is_surfaced_as_the_tools_result_text(self):
- # Throttles are designed to be hit: the message is written for the
- # model and must reach it intact, with the machine detail alongside.
- response = _FakeResponse(
- 429,
- {
- "error": {
- "code": "BFL_GENERATION_COOLDOWN",
- "message": "A new BFL video generation may be started once every 5 minutes. Wait 210 seconds.",
- "details": {"retryAfterSeconds": 210},
- }
- },
- )
-
- parsed, _requests = _call(flux3._handle_text_to_video, {"prompt": "a"}, response)
-
- assert parsed["error"] == "A new BFL video generation may be started once every 5 minutes. Wait 210 seconds."
- assert parsed["details"] == {"retryAfterSeconds": 210}
-
- def test_a_401_asks_for_a_nous_sign_in(self):
- parsed, _requests = _call(flux3._handle_text_to_video, {"prompt": "a"}, _FakeResponse(401, {"error": {"code": "AUTH_ERROR"}}))
-
- assert parsed["needs_reauth"] is True
- assert "sign in" in parsed["error"].lower()
-
- def test_missing_credentials_ask_for_a_sign_in_without_calling_out(self):
- parsed, requests = _call(flux3._handle_text_to_video, {"prompt": "a"}, _FakeResponse(200, {}), headers={})
-
- assert requests == []
- assert "sign in" in parsed["error"].lower()
-
- def test_a_transport_failure_reports_the_cause(self):
- parsed, _requests = _call(
- flux3._handle_text_to_video,
- {"prompt": "a"},
- RuntimeError("connect failed"),
- )
-
- assert "Could not reach the video-generation gateway" in parsed["error"]
- assert "connect failed" in parsed["error"]
-
- def test_an_unreadable_body_does_not_masquerade_as_success(self):
- parsed, _requests = _call(flux3._handle_text_to_video, {"prompt": "a"}, _FakeResponse(502, None, text="upstream exploded"))
-
- assert "error" in parsed
-
-
[email protected](autouse=True)
-def _no_real_poll_wait(monkeypatch):
- """Pace the in-call poll loop off the test clock, at two looks per call.
-
- The handler counts its budget rather than reading a clock, so a gap and a
- budget in a fixed ratio give a deterministic number of looks with no fake
- clock: a budget of two gaps spends one wait and takes two looks, which is
- the smallest loop that can still show a job finishing between looks.
- """
- monkeypatch.setattr(flux3, "_POLL_GAP_SECONDS", 1.0)
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 2.0)
-
- async def _instant(_seconds):
- return None
-
- monkeypatch.setattr(flux3.asyncio, "sleep", _instant)
-
-
-class TestPollTransport:
- def test_a_terminal_status_returns_at_once_without_waiting(self):
- response = _FakeResponse(200, {"id": "bfl_job_1", "status": "Error", "guidance": "The job is over."})
-
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, response)
-
- assert requests[0]["method"] == "GET"
- assert requests[0]["url"] == f"{BASE_URL}/generations/bfl_job_1"
- assert requests[0]["json"] is None
- assert len(requests) == 1
- assert parsed["result"] == "The job is over."
-
- def test_a_running_job_is_waited_out_inside_the_call(self, monkeypatch):
- # A model has no clock, so telling it to pause produced a burst of polls
- # instead of a paced one. The wait lives here where it cannot be skipped.
- monkeypatch.setattr(flux3, "_POLL_GAP_SECONDS", 45.0)
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 90.0)
- running = _FakeResponse(200, {"id": "bfl_job_1", "status": "Generating", "guidance": "Still going."})
-
- slept = []
- with patch.object(flux3.asyncio, "sleep", new=_record_sleep(slept)):
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, running)
-
- assert len(requests) == 2, "should look again after waiting"
- assert sum(slept) == 45.0
- assert parsed["details"]["status"] == "Generating"
-
- def test_the_loop_keeps_looking_until_its_budget_is_spent(self, monkeypatch):
- # The job endpoint answers at once, so a call that looked a fixed twice
- # spent almost none of the time it was allowed and handed control back
- # to the model four or five times per generation. One call now covers
- # the whole budget, and the model decides to keep waiting once.
- monkeypatch.setattr(flux3, "_POLL_GAP_SECONDS", 10.0)
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 50.0)
- running = _FakeResponse(200, {"id": "bfl_job_1", "status": "Generating", "guidance": "Still going."})
-
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, running)
-
- assert len(requests) == 5, "five looks spaced by four ten-second gaps"
- assert parsed["details"]["status"] == "Generating"
-
- def test_the_wait_is_answerable_to_a_stop(self, monkeypatch):
- # Nothing outside the tool can end a call that has already started —
- # the executor only checks for an interrupt between tools — so /stop
- # has to land inside the wait rather than at the end of it.
- monkeypatch.setattr(flux3, "_POLL_GAP_SECONDS", 45.0)
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 200.0)
- from tools import interrupt as interrupt_module
-
- running = _FakeResponse(200, {"id": "bfl_job_1", "status": "Generating", "guidance": "Still going."})
- looks = []
-
- def _stop_after_one_slice():
- looks.append(True)
- return len(looks) > 1
-
- slept = []
- with patch.object(interrupt_module, "is_interrupted", _stop_after_one_slice), \
- patch.object(flux3.asyncio, "sleep", new=_record_sleep(slept)):
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, running)
-
- assert slept == [flux3._POLL_WAIT_SLICE_SECONDS], "the rest of the wait is abandoned"
- assert len(requests) == 1, "and so is the second look"
- assert parsed["details"]["status"] == "Generating"
-
- def test_the_call_returns_as_soon_as_the_job_finishes(self):
- # The point of waiting in here is that the caller gets the result on the
- # wait it was already taking, not one round trip later.
- running = _FakeResponse(200, {"id": "bfl_job_1", "status": "Generating", "guidance": "Still going."})
- done = _FakeResponse(200, {"id": "bfl_job_1", "status": "Error", "guidance": "That job failed."})
-
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, [running, done])
-
- assert len(requests) == 2
- assert parsed["result"] == "That job failed."
-
- def test_a_refusal_without_a_stated_wait_is_returned_immediately(self):
- # A dead job or a bad id has nothing to wait for; sleeping on it would
- # only delay showing the model what to do.
- response = _FakeResponse(429, {"error": {"message": "Too many polls. Wait 30 seconds."}})
-
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, response)
-
- assert len(requests) == 1
- assert "Too many polls" in parsed["error"]
-
- def test_a_throttle_is_waited_out_inside_the_call(self, monkeypatch):
- # Handing a throttle back ends the call, and the model it lands on has
- # no clock — it asks again at once, tightening the loop that tripped the
- # limit. The stated wait is taken here instead.
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 100.0)
- throttled = _FakeResponse(
- 429,
- {"error": {"message": "Too many polls.", "details": {"retryAfterSeconds": 30}}},
- )
- done = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {}, "guidance": "Done."})
-
- slept = []
- with patch.object(flux3.asyncio, "sleep", new=_record_sleep(slept)):
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, [throttled, done])
-
- assert len(requests) == 2, "the loop survives a throttle"
- assert sum(slept) == 30.0, "and waits exactly as long as it was asked to"
- assert parsed["result"] == "Done."
-
- def test_a_throttle_never_polls_faster_than_the_loop_s_own_cadence(self, monkeypatch):
- # The gateway's number is a floor on politeness, not a licence to
- # hammer: a small or malformed-but-positive wait must not turn the loop
- # into a tight one against an endpoint that just asked us to slow down.
- monkeypatch.setattr(flux3, "_POLL_GAP_SECONDS", 10.0)
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 100.0)
- throttled = _FakeResponse(
- 429,
- {"error": {"message": "Slow down.", "details": {"retryAfterSeconds": 0.001}}},
- )
- done = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {}, "guidance": "Done."})
-
- slept = []
- with patch.object(flux3.asyncio, "sleep", new=_record_sleep(slept)):
- _parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, [throttled, done])
-
- assert len(requests) == 2
- assert sum(slept) == 10.0, "the loop's own gap, not the sliver it was offered"
-
- def test_a_slow_poll_spends_the_budget_it_actually_took(self, monkeypatch):
- # Counting only the waits would let a gateway that answers slowly run
- # the call far past its budget, leaving the backstop to do the work the
- # budget is supposed to do. A look costs what it takes.
- monkeypatch.setattr(flux3, "_POLL_GAP_SECONDS", 1.0)
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 30.0)
- running = _FakeResponse(200, {"id": "bfl_job_1", "status": "Generating", "guidance": "Still going."})
-
- monkeypatch.setattr(flux3, "time", SimpleNamespace(monotonic=_stepped_clock(20.0)))
-
- _parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, running)
-
- assert len(requests) == 2, "two twenty-second looks exhaust a thirty-second budget"
-
- def test_a_poll_outwaits_the_gateways_own_poll_budget(self):
- # The gateway bounds one status read at 45s across its retries and
- # regional redirect hops. Giving up before it does turns a slow but
- # healthy poll into a transport error, and an error ends the loop.
- assert flux3._POLL_READ_TIMEOUT_SECONDS > 45.0
-
- def test_a_blip_costs_a_look_rather_than_the_rest_of_the_call(self, monkeypatch):
- # The generation runs upstream and is unaffected by our failing to ask
- # about it, so one unreachable moment must not throw away the minutes
- # of budget left. Returning it would end the call on an error the model
- # can only answer by polling again at once — the burst the loop exists
- # to prevent.
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 100.0)
- done = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {}, "guidance": "Done."})
-
- parsed, requests = _call(
- flux3._handle_get_result,
- {"id": "bfl_job_1"},
- [RuntimeError("connection reset"), done],
- )
-
- assert len(requests) == 2, "the loop looked again after the blip"
- assert parsed["result"] == "Done."
-
- def test_a_gateway_answering_in_html_counts_as_unreachable(self, monkeypatch):
- # What a 502 from an edge in front of the gateway looks like from here:
- # a status code and a page, with no error the model could act on. That
- # is an absent answer, not a refusal, so it is retried like one.
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 100.0)
- done = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {}, "guidance": "Done."})
-
- _parsed, requests = _call(
- flux3._handle_get_result,
- {"id": "bfl_job_1"},
- [_FakeResponse(502, None, text="<html>bad gateway</html>"), done],
- )
-
- assert len(requests) == 2
-
- def test_a_gateway_that_stays_down_is_reported_rather_than_retried_out(self, monkeypatch):
- # Tolerance is for blips. A gateway that is genuinely down has to reach
- # the model promptly, not after minutes of a budget spent on a host
- # that is not answering.
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 1000.0)
-
- parsed, requests = _call(
- flux3._handle_get_result,
- {"id": "bfl_job_1"},
- RuntimeError("connection reset"),
- )
-
- assert len(requests) == flux3._MAX_CONSECUTIVE_TRANSPORT_ERRORS
- assert "Could not reach" in parsed["error"]
-
- def test_the_tolerance_counts_consecutive_failures_only(self, monkeypatch):
- # A flaky gateway that answers every other look is still usable, so the
- # count has to reset on an answer rather than accumulate over the call.
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 1000.0)
- blip = RuntimeError("connection reset")
- running = _FakeResponse(200, {"id": "bfl_job_1", "status": "Generating", "guidance": "Still going."})
- done = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {}, "guidance": "Done."})
-
- parsed, requests = _call(
- flux3._handle_get_result,
- {"id": "bfl_job_1"},
- [blip, blip, running, blip, blip, done],
- )
-
- assert len(requests) == 6, "four blips, never three in a row, so the call survives"
- assert parsed["result"] == "Done."
-
- def test_a_throttle_longer_than_the_budget_is_handed_back(self, monkeypatch):
- # A five-minute generation cooldown cannot be absorbed inside one call,
- # so the model gets the message and the number rather than a call that
- # sits out a wait it can never finish.
- monkeypatch.setattr(flux3, "_POLL_BUDGET_SECONDS", 100.0)
- response = _FakeResponse(
- 429,
- {"error": {"message": "Wait 210 seconds.", "details": {"retryAfterSeconds": 210}}},
- )
-
- parsed, requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, response)
-
- assert len(requests) == 1
- assert parsed["error"] == "Wait 210 seconds."
-
- def test_the_backstop_answers_rather_than_letting_the_bridge_kill_the_call(self, monkeypatch):
- # model_tools' async bridge abandons a tool at 300s and reports it as a
- # bare "TimeoutError:" — no job id, nothing to say the generation is
- # still alive and one poll away. Whatever stalls inside, the model is
- # answered from here first.
- monkeypatch.setattr(flux3, "_CALL_BACKSTOP_SECONDS", 0.01)
-
- async def _never_finishes(*_args, **_kwargs):
- await asyncio.Event().wait()
-
- monkeypatch.setattr(flux3, "_poll_until_done", _never_finishes)
-
- parsed, _requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, _FakeResponse(200, {}))
-
- assert parsed["details"] == {"id": "bfl_job_1", "status": "Generating"}
- assert "bfl_flux3_get_result" in parsed["result"]
- assert "bfl_job_1" in parsed["result"]
-
- def test_a_poll_does_not_inherit_the_submit_read_timeout(self):
- # A status GET answers at once. Left on the submit path's patience, one
- # hung poll would spend the whole call's budget by itself — while submit,
- # which really does sit behind an upload and an upstream call, keeps it.
- import httpx
-
- timeouts = []
- sink = []
- settled = _FakeResponse(200, {"id": "j", "status": "Error", "guidance": "over"})
-
- def _client(**kwargs):
- timeouts.append(kwargs.get("timeout"))
- return _FakeClient(settled, sink)
-
- with patch.object(flux3, "managed_gateway_auth_headers", return_value={"Authorization": "Bearer t"}), \
- patch.object(httpx, "AsyncClient", _client):
- _run(flux3._handle_get_result({"id": "j"}))
- _run(flux3._handle_text_to_video({"prompt": "a"}))
-
- poll_timeout, submit_timeout = timeouts
- assert poll_timeout.read == flux3._POLL_READ_TIMEOUT_SECONDS
- assert submit_timeout.read == flux3._TRANSPORT_READ_TIMEOUT_SECONDS
- assert poll_timeout.read < submit_timeout.read
-
- def test_the_pacing_stays_clear_of_the_agents_per_tool_ceiling(self):
- # The whole point of the two bounds: a clip finishing on the last look
- # still has to be downloaded inside the backstop, and the backstop has
- # to answer before model_tools' async bridge abandons the tool at 300s.
- assert _DEFAULT_POLL_BUDGET_SECONDS < _DEFAULT_CALL_BACKSTOP_SECONDS
- assert _DEFAULT_CALL_BACKSTOP_SECONDS < 300.0
-
- def test_download_timeout_never_outlives_the_backstop(self):
- # Near the end of the call, remaining budget after grace is a few
- # seconds. Clamping that up used to schedule a download the outer
- # wait_for then cancelled, answering "still generating" for a Ready job.
- started = time.monotonic() - (
- flux3._CALL_BACKSTOP_SECONDS - flux3._DOWNLOAD_GRACE_SECONDS - 2.0
- )
- assert flux3._download_read_timeout(started) <= 2.0 + 0.5 # clock noise only
-
- def test_ready_saves_the_clip_and_never_returns_the_signed_url(self, tmp_path):
- # The signed URL is a bearer credential for the clip and it used to be
- # re-keyed into a shell command by hand, dropping characters. Neither
- # can happen if the model never sees it.
- signed = "https://cdn.example/container/flux3-clip.mp4?sig=abc%2Bdef%3D&se=2026"
- response = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {"sample": signed}, "guidance": "Deliver the saved file."})
-
- with _fake_download(b"x" * (128 * 1024)) as fetched:
- parsed, _requests = _call(
- flux3._handle_get_result,
- {"id": "bfl_job_1", "save_to": str(tmp_path)},
- response,
- )
-
- saved = tmp_path / "flux3-clip.mp4"
- assert saved.read_bytes() == b"x" * (128 * 1024)
- assert parsed["details"]["saved_path"] == str(saved)
- assert parsed["details"]["result"].get("sample") is None
- assert signed not in json.dumps(parsed)
- # The gateway still owns the delivery wording; the client only supplies
- # the path it cannot know.
- assert parsed["result"].startswith(f"Saved to {saved}.")
- assert "Deliver the saved file." in parsed["result"]
- assert fetched == [signed]
-
- def test_ready_never_overwrites_an_existing_file(self, tmp_path):
- (tmp_path / "flux3-clip.mp4").write_bytes(b"an earlier clip")
- response = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {"sample": "https://cdn.example/x/flux3-clip.mp4?sig=a"}, "guidance": "g"})
-
- with _fake_download(b"y" * (128 * 1024)):
- parsed, _requests = _call(flux3._handle_get_result, {"id": "bfl_job_1", "save_to": str(tmp_path)}, response)
-
- assert parsed["details"]["saved_path"] == str(tmp_path / "flux3-clip-2.mp4")
- assert (tmp_path / "flux3-clip.mp4").read_bytes() == b"an earlier clip"
-
- def test_on_messaging_the_clip_lands_where_the_gateway_may_send_it(self, monkeypatch):
- # A chat user has no filesystem: the attachment is the only way they
- # ever see the clip. Downloads is not a delivery root on a strict
- # gateway, so a clip saved there is dropped on the way out and the
- # reply arrives with nothing attached.
- monkeypatch.setenv("HERMES_SESSION_PLATFORM", "telegram")
- monkeypatch.setenv("HERMES_MEDIA_DELIVERY_STRICT", "1")
- # Strict mode also trusts anything written in the last 10 minutes, and
- # a clip we just downloaded is always inside that window. Left on, the
- # assertion below passes from any directory on earth and stops being a
- # statement about where the clip was saved.
- monkeypatch.setenv("HERMES_MEDIA_TRUST_RECENT_FILES", "0")
- response = _FakeResponse(200, {
- "id": "bfl_job_1",
- "status": "Ready",
- "result": {"sample": "https://cdn.example/x/flux3-clip.mp4?sig=a"},
- "guidance": "Deliver the saved file.",
- })
-
- with _fake_download(b"x" * (128 * 1024)):
- parsed, _requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, response)
-
- from gateway.platforms.base import validate_media_delivery_path
-
- saved = parsed["details"]["saved_path"]
- assert validate_media_delivery_path(saved), "the gateway must be allowed to send it"
- # The exact line to copy, so the path is never retyped from memory.
- assert f"\nMEDIA:{saved}\n" in parsed["result"]
-
- def test_the_offered_tag_is_one_the_gateway_actually_delivers(self, monkeypatch):
- # The whole point of spelling the line out is that the model pastes it
- # verbatim, so the line has to survive the real extractor. A tag that
- # parses but fails validation is the worst outcome: it is stripped from
- # the reply either way, so the user is shown a message that looks like
- # it simply forgot the attachment.
- monkeypatch.setenv("HERMES_SESSION_PLATFORM", "telegram")
- response = _FakeResponse(200, {
- "id": "bfl_job_1",
- "status": "Ready",
- "result": {"sample": "https://cdn.example/x/flux3-clip.mp4?sig=a"},
- "guidance": "Deliver the saved file.",
- })
-
- with _fake_download(b"x" * (128 * 1024)):
- parsed, _requests = _call(flux3._handle_get_result, {"id": "bfl_job_1"}, response)
-
- from gateway.platforms.base import BasePlatformAdapter
-
- offered = [ln for ln in parsed["result"].splitlines() if ln.startswith("MEDIA:")]
- assert len(offered) == 1, "exactly one line to copy"
-
- reply = f"Here's the clip.\n\n{offered[0]}\n"
- media, cleaned = BasePlatformAdapter.extract_media(reply)
- assert BasePlatformAdapter.filter_media_delivery_paths(media), "must survive validation"
- assert "MEDIA:" not in cleaned, "the tag is consumed, not shown to the user"
-
- @pytest.mark.parametrize("platform", ["", "cli", "tui", "desktop"])
- def test_off_messaging_the_clip_stays_a_file_and_no_tag_is_offered(self, tmp_path, monkeypatch, platform):
- # The CLI has no attachment channel and its prompt forbids the tag —
- # emitting one there just prints literal text at the user.
- monkeypatch.setenv("HERMES_SESSION_PLATFORM", platform)
- response = _FakeResponse(200, {
- "id": "bfl_job_1",
- "status": "Ready",
- "result": {"sample": "https://cdn.example/x/flux3-clip.mp4?sig=a"},
- "guidance": "Deliver the saved file.",
- })
-
- with _fake_download(b"x" * (128 * 1024)):
- parsed, _requests = _call(
- flux3._handle_get_result, {"id": "bfl_job_1", "save_to": str(tmp_path)}, response,
- )
-
- assert parsed["result"].startswith(f"Saved to {tmp_path / 'flux3-clip.mp4'}.")
- assert "MEDIA:" not in parsed["result"]
-
- @pytest.mark.parametrize("platform", ["api_server", "webhook", "msgraph_webhook", "local"])
- def test_platforms_without_an_attachment_channel_are_offered_no_tag(self, tmp_path, monkeypatch, platform):
- # These carry a real platform value but no way to attach a file. The
- # API server in particular only inlines *images* as data URLs and
- # leaves every other MEDIA: tag untouched, so offering one here puts
- # the literal text in front of an OpenAI-compatible caller.
- monkeypatch.setenv("HERMES_SESSION_PLATFORM", platform)
- response = _FakeResponse(200, {
- "id": "bfl_job_1",
- "status": "Ready",
- "result": {"sample": "https://cdn.example/x/flux3-clip.mp4?sig=a"},
- "guidance": "Deliver the saved file.",
- })
-
- with _fake_download(b"x" * (128 * 1024)):
- parsed, _requests = _call(
- flux3._handle_get_result, {"id": "bfl_job_1", "save_to": str(tmp_path)}, response,
- )
-
- assert "MEDIA:" not in parsed["result"]
-
- def test_a_cli_session_is_recognised_by_its_source(self, tmp_path, monkeypatch):
- # The CLI, TUI, and desktop leave HERMES_SESSION_PLATFORM empty and
- # identify themselves on HERMES_SESSION_SOURCE instead, so keying only
- # on the platform would miss them.
- monkeypatch.delenv("HERMES_SESSION_PLATFORM", raising=False)
- monkeypatch.setenv("HERMES_SESSION_SOURCE", "tui")
- response = _FakeResponse(200, {
- "id": "bfl_job_1",
- "status": "Ready",
- "result": {"sample": "https://cdn.example/x/flux3-clip.mp4?sig=a"},
- "guidance": "Deliver the saved file.",
- })
-
- with _fake_download(b"x" * (128 * 1024)):
- parsed, _requests = _call(
- flux3._handle_get_result, {"id": "bfl_job_1", "save_to": str(tmp_path)}, response,
- )
-
- assert "MEDIA:" not in parsed["result"]
-
- def test_a_rejected_download_fails_loudly_and_leaves_no_file(self, tmp_path):
- # The original bug: a bad signature returns an XML error body, curl
- # writes it to the .mp4 and exits 0, and it reads as success. A short
- # body is not a video whatever the status code said.
- response = _FakeResponse(200, {"id": "bfl_job_1", "status": "Ready", "result": {"sample": "https://cdn.example/x/flux3-clip.mp4?sig=bad"}, "guidance": "g"})
-
- with _fake_download(b"<?xml version='1.0'?><Error>AuthenticationFailed</Error>"):
- parsed, _requests = _call(flux3._handle_get_result, {"id": "bfl_job_1", "save_to": str(tmp_path)}, response)
-
- assert "saving it failed" in parsed["result"]
- assert "Poll this job again" in parsed["result"]
- # Neither a half-written .part nor a plausible-looking .mp4 survives.
- assert [p.name for p in tmp_path.glob("*.mp4*")] == []
- assert "saved_path" not in parsed["details"]
-
- def test_poll_requires_an_id(self):
- parsed, requests = _call(flux3._handle_get_result, {}, _FakeResponse(200, {}))
-
- assert "id is required" in parsed["error"]
- assert requests == []
-
- def test_poll_url_encodes_the_job_id(self):
- _parsed, requests = _call(
- flux3._handle_get_result,
- {"id": "weird/../id"},
- _FakeResponse(200, {"id": "x", "guidance": "ok"}),
- )
- assert requests[0]["url"] == f"{BASE_URL}/generations/weird%2F..%2Fid"
-
-
-class TestMediaDelivery:
- def _resolved(self, mime="image/png", data=_PNG):
- return SimpleNamespace(data=data, mime=mime)
-
- def test_a_local_path_is_uploaded_and_replaced_with_a_reference(self):
- async def fake_uploader(data, mime):
- assert data == _PNG
- assert mime == "image/png"
- return "nous-upload:token-1"
-
- with patch.object(flux3, "build_managed_media_uploader", return_value=fake_uploader), patch(
- "tools.image_source.resolve_image_source", return_value=self._resolved()
- ) as resolve:
- _parsed, requests = _call(
- flux3._handle_image_to_video,
- {"prompt": "a", "input_image": "/tmp/frame.png"},
- _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}),
- )
-
- assert requests[0]["json"]["input_image"] == "nous-upload:token-1"
- # Images and video ride the same safety pipeline; only the permitted
- # type differs, and an image field must not accept a video.
- assert resolve.call_args.kwargs["permitted"] == ("image",)
-
- def test_video_fields_permit_video_only(self):
- async def fake_uploader(data, mime):
- return "nous-upload:token-v"
-
- with patch.object(flux3, "build_managed_media_uploader", return_value=fake_uploader), patch(
- "tools.image_source.resolve_image_source", return_value=self._resolved("video/mp4", b"\x00\x00\x00\x18ftypmp42")
- ) as resolve:
- _parsed, requests = _call(
- flux3._handle_video_continuation,
- {"prompt": "a", "input_video": "/tmp/clip.mp4"},
- _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}),
- )
-
- assert requests[0]["json"]["input_video"] == "nous-upload:token-v"
- assert resolve.call_args.kwargs["permitted"] == ("video",)
-
- def test_every_keyframe_path_is_uploaded(self):
- uploads = []
-
- async def fake_uploader(data, mime):
- uploads.append(mime)
- return f"nous-upload:token-{len(uploads)}"
-
- with patch.object(flux3, "build_managed_media_uploader", return_value=fake_uploader), patch(
- "tools.image_source.resolve_image_source", return_value=self._resolved()
- ):
- _parsed, requests = _call(
- flux3._handle_keyframes_to_video,
- {"prompt": "a", "input_images": ["/tmp/a.png", "https://x/b.png", "/tmp/c.png"], "keyframe_indices": [0, 24, 48]},
- _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}),
- )
-
- # The URL in the middle is forwarded untouched.
- assert requests[0]["json"]["input_images"] == [
- "nous-upload:token-1",
- "https://x/b.png",
- "nous-upload:token-2",
- ]
-
- def test_a_list_valued_input_image_is_still_uploaded(self):
- # The gateway accepts input_image as a string OR a list, so a list of
- # local paths must not slip past unsanitized — that would send raw
- # filesystem paths to the vendor and disclose the user's directories.
- async def fake_uploader(data, mime):
- return "nous-upload:token-1"
-
- with patch.object(flux3, "build_managed_media_uploader", return_value=fake_uploader), patch(
- "tools.image_source.resolve_image_source", return_value=self._resolved()
- ):
- _parsed, requests = _call(
- flux3._handle_image_to_video,
- {"prompt": "a", "input_image": ["/tmp/frame.png"]},
- _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}),
- )
-
- assert requests[0]["json"]["input_image"] == ["nous-upload:token-1"]
- assert "/tmp/frame.png" not in json.dumps(requests[0]["json"])
-
- def test_media_fields_are_sanitized_whatever_the_mode_expects(self):
- # The gateway prefers input_image over input_images, so sanitizing only
- # the field this mode documents would let the other one through.
- uploads = []
-
- async def fake_uploader(data, mime):
- uploads.append(mime)
- return f"nous-upload:token-{len(uploads)}"
-
- with patch.object(flux3, "build_managed_media_uploader", return_value=fake_uploader), patch(
- "tools.image_source.resolve_image_source", return_value=self._resolved()
- ):
- _parsed, requests = _call(
- flux3._handle_keyframes_to_video,
- {
- "prompt": "a",
- "input_images": ["https://x/b.png"],
- "input_image": "/tmp/sneaky.png",
- "keyframe_indices": [0],
- },
- _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}),
- )
-
- body = json.dumps(requests[0]["json"])
- assert "/tmp/sneaky.png" not in body
- assert requests[0]["json"]["input_image"] == "nous-upload:token-1"
-
- def test_text_to_video_strips_media_fields_instead_of_uploading_them(self):
- # The mode takes no media, so an upload would spend the caller's quota
- # on a value the gateway ignores.
- def _must_not_upload(*_args, **_kwargs):
- raise AssertionError("text-to-video must not upload anything")
-
- with patch.object(flux3, "build_managed_media_uploader", _must_not_upload):
- _parsed, requests = _call(
- flux3._handle_text_to_video,
- {"prompt": "a", "input_image": "/tmp/frame.png"},
- _FakeResponse(200, {"id": "j", "status": "submitted", "guidance": "ok"}),
- )
-
- assert "input_image" not in requests[0]["json"]
- assert requests[0]["json"]["mode"] == "text_to_video"
-
- def test_an_over_long_image_list_is_refused_before_any_upload(self):
- def _must_not_upload(*_args, **_kwargs):
- raise AssertionError("an over-long list must be refused before uploading")
-
- with patch.object(flux3, "build_managed_media_uploader", _must_not_upload):
- parsed, requests = _call(
- flux3._handle_keyframes_to_video,
- {"prompt": "a", "input_images": [f"/tmp/{i}.png" for i in range(11)], "keyframe_indices": [0]},
- _FakeResponse(200, {}),
- )
-
- assert "at most 10" in parsed["error"]
- assert requests == []
-
- def test_an_upload_refusal_becomes_the_tools_error(self):
- async def failing_uploader(data, mime):
- raise RuntimeError("the daily upload budget for this account is exhausted")
-
- with patch.object(flux3, "build_managed_media_uploader", return_value=failing_uploader), patch(
- "tools.image_source.resolve_image_source", return_value=self._resolved()
- ):
- parsed, requests = _call(
- flux3._handle_image_to_video,
- {"prompt": "a", "input_image": "/tmp/frame.png"},
- _FakeResponse(200, {}),
- )
-
- assert "daily upload budget" in parsed["error"]
- # A failed upload must not reach the gateway as a bare local path.
- assert requests == []
-
- def test_an_unreadable_file_is_reported_without_dumping_the_value(self):
- from tools.image_source import SourceNotFound
-
- with patch.object(flux3, "build_managed_media_uploader", return_value=lambda *a: None), patch(
- "tools.image_source.resolve_image_source", side_effect=SourceNotFound("media file not found", src="/tmp/x.png")
- ):
- parsed, requests = _call(
- flux3._handle_image_to_video,
- # Long, but unmistakably a path (dots and dashes are outside
- # the base64 alphabet, so the payload guard leaves it alone).
- {"prompt": "a", "input_image": "/tmp/" + "a-b." * 2000 + "frame.png"},
- _FakeResponse(200, {}),
- )
-
- assert "error" in parsed
- # The offending value is truncated: echoing it whole would blow up the
- # model's context on the way to reporting a bad path.
- assert len(parsed["error"]) < 500
- assert requests == []
-
-
-class TestLocalPathDetection:
- @pytest.mark.parametrize(
- "value",
- ["/tmp/frame.png", "~/Pictures/f.png", "./f.png", "../f.png", "file:///tmp/f.png", r"C:\Users\me\f.png", r"\\nas\share\f.png"],
- )
- def test_rooted_paths_are_read_off_disk(self, value):
- assert flux3._looks_like_local_path(value) is True
-
- @pytest.mark.parametrize(
- "value",
- [
- "frame.png",
- "https://example.com/f.png",
- "nous-upload:eyJhbGciOiJIUzI1NiJ9.e30.sig",
- "C:frame.png",
- # Inline base64 of a JPEG always starts "/9j/" (first byte 0xFF),
- # which must not read as an absolute POSIX path.
- "/9j/4AAQSkZJRgABAQAAAQ" + "A" * 300 + "==",
- ],
- )
- def test_ambiguous_and_remote_values_are_forwarded(self, value):
- assert flux3._looks_like_local_path(value) is False
-
- def test_a_short_base64_lookalike_path_is_still_a_path(self):
- assert flux3._looks_like_local_path("/tmp/frames/a1") is True
-
-
-class TestSchemas:
- def test_every_tool_is_registered_under_the_bfl_toolset(self):
- from tools.registry import registry
-
- for name in [
- "bfl_flux3_text_to_video",
- "bfl_flux3_image_to_video",
- "bfl_flux3_keyframes_to_video",
- "bfl_flux3_video_continuation",
- "bfl_flux3_get_result",
- "bfl_flux3_prompting_guide",
- ]:
- entry = registry.get_entry(name)
- assert entry is not None, f"{name} is not registered"
- assert entry.toolset == "bfl"
- assert entry.check_fn is flux3.check_bfl_requirements
-
- def test_generate_tools_point_at_the_guide_and_the_poll_tool(self):
- # Descriptions are the only text guaranteed to be in context when a
- # model picks a tool, so the pointers live there.
- for schema in [flux3.TEXT_TO_VIDEO_SCHEMA, flux3.IMAGE_TO_VIDEO_SCHEMA, flux3.KEYFRAMES_TO_VIDEO_SCHEMA, flux3.VIDEO_CONTINUATION_SCHEMA]:
- assert "bfl_flux3_prompting_guide" in schema["description"]
- assert "bfl_flux3_get_result" in schema["description"]
-
- def test_the_guide_covers_the_methodology_without_pinning_server_policy(self):
- guide = flux3.FLUX3_PROMPTING_GUIDE
- assert "grounding" in guide.lower()
- assert "bfl_flux3_get_result" in guide
- # Waits and limits ship live in the gateway's responses; pinning them
- # here would let the client lie about what the server enforces.
- assert "5 minutes" not in guide
- assert "per minute" not in guide
-
- def test_the_guide_tool_takes_no_arguments_and_calls_nothing(self):
- assert flux3.PROMPTING_GUIDE_SCHEMA["parameters"]["properties"] == {}
- assert _run(flux3._handle_prompting_guide({})) == flux3.FLUX3_PROMPTING_GUIDE
diff --git a/tests/tools/test_managed_tool_gateway.py b/tests/tools/test_managed_tool_gateway.py
index 3e281b0c696..f690cf8dc2c 100644
--- a/tests/tools/test_managed_tool_gateway.py
+++ b/tests/tools/test_managed_tool_gateway.py
@@ -116,12 +116,12 @@ def test_managed_vendor_endpoints_pin_the_deployed_gateway_url():
clear=False,
):
os.environ.pop("TOOL_GATEWAY_URL", None)
- endpoints = managed_tool_gateway.managed_vendor_endpoints("bfl")
+ endpoints = managed_tool_gateway.managed_vendor_endpoints("vendorx")
assert endpoints == {
"origin": "https://tool-gateway.nousresearch.com",
- "base_url": "https://tool-gateway.nousresearch.com/api/bfl",
- "upload_path": "/api/uploads/bfl",
+ "base_url": "https://tool-gateway.nousresearch.com/api/vendorx",
+ "upload_path": "/api/uploads/vendorx",
}
@@ -139,10 +139,10 @@ def test_managed_vendor_endpoints_do_not_consult_entitlement():
side_effect=AssertionError("entitlement must not gate address resolution"),
):
os.environ.pop("TOOL_GATEWAY_URL", None)
- endpoints = managed_tool_gateway.managed_vendor_endpoints("bfl")
+ endpoints = managed_tool_gateway.managed_vendor_endpoints("vendorx")
assert endpoints is not None
- assert endpoints["base_url"] == "https://tool-gateway.nousresearch.com/api/bfl"
+ assert endpoints["base_url"] == "https://tool-gateway.nousresearch.com/api/vendorx"
def test_managed_vendor_endpoints_are_none_when_no_origin_resolves():
@@ -150,13 +150,13 @@ def test_managed_vendor_endpoints_are_none_when_no_origin_resolves():
# that rather than building a URL out of a broken setting.
with patch.dict(os.environ, {"TOOL_GATEWAY_SCHEME": "ftp"}, clear=False):
os.environ.pop("TOOL_GATEWAY_URL", None)
- assert managed_tool_gateway.managed_vendor_endpoints("bfl") is None
+ assert managed_tool_gateway.managed_vendor_endpoints("vendorx") is None
def test_managed_gateway_auth_headers_carry_the_bearer():
with patch.object(managed_tool_gateway, "managed_nous_tools_enabled", return_value=True):
headers = managed_tool_gateway.managed_gateway_auth_headers(
- "https://tool-gateway.example.com/api/bfl/generations",
+ "https://tool-gateway.example.com/api/vendorx/generations",
gateway_builder=lambda vendor: f"https://{vendor}-gateway.example.com",
token_reader=lambda: "nous-token",
)
@@ -169,7 +169,7 @@ def test_managed_gateway_auth_headers_reflect_a_rotated_token():
# and a long session must not keep presenting a dead bearer.
tokens = iter(["first-token", "second-token"])
builder = lambda vendor: f"https://{vendor}-gateway.example.com"
- url = "https://tool-gateway.example.com/api/bfl/generations"
+ url = "https://tool-gateway.example.com/api/vendorx/generations"
with patch.object(managed_tool_gateway, "managed_nous_tools_enabled", return_value=True):
first = managed_tool_gateway.managed_gateway_auth_headers(url, builder, lambda: next(tokens))
@@ -184,7 +184,7 @@ def test_managed_gateway_auth_headers_refuse_a_url_off_the_gateway_origin():
# host that merely looks managed.
with patch.object(managed_tool_gateway, "managed_nous_tools_enabled", return_value=True):
assert managed_tool_gateway.managed_gateway_auth_headers(
- "https://attacker.example/api/bfl/generations",
+ "https://attacker.example/api/vendorx/generations",
gateway_builder=lambda vendor: f"https://{vendor}-gateway.example.com",
token_reader=lambda: "nous-token",
) == {}
@@ -195,7 +195,7 @@ def test_managed_gateway_auth_headers_empty_without_a_token():
# sending an unauthenticated request.
with patch.object(managed_tool_gateway, "managed_nous_tools_enabled", return_value=True):
assert managed_tool_gateway.managed_gateway_auth_headers(
- "https://tool-gateway.example.com/api/bfl/generations",
+ "https://tool-gateway.example.com/api/vendorx/generations",
gateway_builder=lambda vendor: f"https://{vendor}-gateway.example.com",
token_reader=lambda: None,
) == {}
@@ -211,8 +211,8 @@ class TestManagedMediaUploader:
"""
GATEWAY = "https://tool-gateway.example.com"
- BASE_URL = f"{GATEWAY}/api/bfl"
- UPLOAD_PATH = "/api/uploads/bfl"
+ BASE_URL = f"{GATEWAY}/api/vendorx"
+ UPLOAD_PATH = "/api/uploads/vendorx"
def _uploader(self, **kwargs):
return managed_tool_gateway.build_managed_media_uploader(
@@ -314,9 +314,9 @@ class TestManagedMediaUploader:
# Refusing to build is what makes the caller say "pass a URL instead"
# rather than forwarding a raw local path to a third party.
with patch.object(managed_tool_gateway, "managed_nous_tools_enabled", return_value=True):
- assert self._uploader(server_url="https://attacker.example/api/bfl") is None
+ assert self._uploader(server_url="https://attacker.example/api/vendorx") is None
- @pytest.mark.parametrize("upload_path", [None, "", "api/uploads/bfl", 42])
+ @pytest.mark.parametrize("upload_path", [None, "", "api/uploads/vendorx", 42])
def test_no_uploader_without_a_rooted_upload_path(self, upload_path):
with patch.object(managed_tool_gateway, "managed_nous_tools_enabled", return_value=True):
assert self._uploader(upload_path=upload_path) is None
diff --git a/tools/flux3_video_tool.py b/tools/flux3_video_tool.py
deleted file mode 100644
index 8f7ae6754fb..00000000000
--- a/tools/flux3_video_tool.py
+++ /dev/null
@@ -1,1249 +0,0 @@
-"""Native BFL FLUX 3 video generation tools, backed by the Nous tool gateway.
-
-These are native tools in the ``image_generate`` mold: schemas and
-descriptions are pinned here as build-time facts, the handlers speak the
-gateway's own REST contract, and ``check_fn`` hides the whole toolset only when
-there is no Nous sign-in to call it with — never on entitlement, which is the
-gateway's to rule on. No runtime discovery, and no server-supplied schema is
-ever consulted — that is the point of the design.
-
-The wire is two calls against the gateway's managed mount, and it names the
-vendor but not the vendor's API:
-
-- ``POST {base}/generations`` with ``{mode, prompt, ...}`` -> ``{id, status,
- guidance}``
-- ``GET {base}/generations/<id>`` -> the job state plus ``guidance``
-
-``guidance`` is the gateway's live policy channel: exact waits, what to do
-next, and how to deliver a finished clip ship from the server so they cannot
-drift from what it actually enforces. Handlers surface it verbatim as the
-tool's result text, and surface ``error.message`` the same way on a refusal.
-
-Media inputs: handlers know their own media fields explicitly. A local file
-path is resolved through :func:`tools.image_source.resolve_image_source`
-(sandbox confinement, credential guard) and delivered via the Nous upload
-protocol (presign, direct PUT to storage, ``nous-upload:<token>`` reference).
-URLs pass through untouched.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import json
-import logging
-import re
-import time
-from typing import Optional
-
-from tools.registry import registry
-from tools.managed_tool_gateway import (
- build_managed_media_uploader,
- managed_gateway_auth_headers,
- managed_vendor_endpoints,
- peek_nous_access_token,
- read_nous_access_token,
-)
-
-logger = logging.getLogger(__name__)
-
-_TOOLSET = "bfl"
-_VENDOR = "bfl"
-
-# Submit sits behind the gateway's upstream call plus upload-reference
-# resolution, so it is given a generous read timeout. A poll passes its own,
-# much shorter one (see _POLL_READ_TIMEOUT_SECONDS): the job endpoint answers
-# at once, and a poll allowed to hang this long would spend the whole call.
-_TRANSPORT_READ_TIMEOUT_SECONDS = 180.0
-_TRANSPORT_CONNECT_TIMEOUT_SECONDS = 10.0
-
-_SIGN_IN_MESSAGE = (
- "BFL video generation needs a Nous Portal sign-in. "
- "Ask the user to run `hermes model` and sign in to Nous, then retry."
-)
-
-# ---------------------------------------------------------------------------
-# Local-path detection (moved from the retired MCP media-argument walker)
-# ---------------------------------------------------------------------------
-
-# Drive-absolute Windows paths: ``C:\Users\...`` / ``C:/Users/...``.
-_WINDOWS_DRIVE_PATH = re.compile(r"^[A-Za-z]:[\\/]")
-
-# A whole string of base64 alphabet (optionally line-wrapped, optionally
-# padded). Base64's alphabet includes "/", so an inline JPEG payload always
-# starts with "/9j/" — which reads as an absolute path unless caught first.
-_BASE64_PAYLOAD = re.compile(r"^[A-Za-z0-9+/\r\n]+={0,2}[\r\n]*$")
-# Real filesystem paths are short; base64 of even a thumbnail runs to
-# thousands of characters. Anything this long and alphabet-pure is a payload.
-_MIN_BASE64_PAYLOAD_LENGTH = 256
-
-
-def _looks_like_local_path(value: str) -> bool:
- """True for things we should read off disk rather than forward as-is.
-
- Deliberately narrow: only explicitly rooted paths and ``file://`` qualify.
- Bare names are ambiguous with opaque ids, URLs pass through, and base64
- payloads (checked first — a JPEG's base64 starts ``/9j/``) fall through
- untouched.
- """
- if len(value) >= _MIN_BASE64_PAYLOAD_LENGTH and _BASE64_PAYLOAD.match(value):
- return False
- if value.startswith("file://"):
- return True
- if value == "~" or value.startswith(("~/", "~\\")):
- return True
- if value.startswith(("/", "./", "../", ".\\", "..\\")):
- return True
- if _WINDOWS_DRIVE_PATH.match(value) or value.startswith("\\\\"):
- return True
- return False
-
-
-def _display_path(path: str) -> str:
- """A value safe to embed in an error message shown to the model."""
- return path if len(path) <= 200 else f"{path[:200]}… ({len(path)} characters)"
-
-
-# ---------------------------------------------------------------------------
-# Gateway transport
-# ---------------------------------------------------------------------------
-
-def _endpoints() -> Optional[dict]:
- """Absolute URLs for the managed BFL routes, or None when unreachable."""
- return managed_vendor_endpoints(_VENDOR)
-
-
-async def _call_gateway(
- method: str,
- url: str,
- json_body: Optional[dict] = None,
- read_timeout: Optional[float] = None,
-) -> str:
- """One REST round trip, rendered as this tool's result.
-
- The gateway's ``guidance`` (on success) and ``error.message`` (on a
- refusal) are both written for a model to act on, so they are surfaced
- verbatim. A refusal is a normal outcome the model can respond to — being
- throttled is not a broken tool — so only genuinely unreadable responses
- become ``error``.
-
- Those unreadable ones carry ``transport_error`` as well. A refusal is the
- gateway's ruling on the request; a transport failure is the absence of one,
- and says nothing about the job. The poll loop tells them apart on that key
- rather than on the wording of a message.
- """
- import httpx
-
- headers = managed_gateway_auth_headers(url)
- if not headers:
- return json.dumps({"error": _SIGN_IN_MESSAGE})
- headers["Content-Type"] = "application/json"
-
- timeout = httpx.Timeout(
- _TRANSPORT_CONNECT_TIMEOUT_SECONDS,
- read=_TRANSPORT_READ_TIMEOUT_SECONDS if read_timeout is None else read_timeout,
- )
- try:
- async with httpx.AsyncClient(timeout=timeout) as client:
- response = await client.request(method, url, headers=headers, json=json_body)
- except Exception as exc:
- return json.dumps({
- "error": f"Could not reach the video-generation gateway: {type(exc).__name__}: {exc}",
- "transport_error": True,
- })
-
- if response.status_code == 401:
- return json.dumps({"error": _SIGN_IN_MESSAGE, "needs_reauth": True})
-
- try:
- payload = response.json()
- except Exception:
- payload = None
-
- if not isinstance(payload, dict):
- # An edge or a proxy answering in HTML rather than the gateway itself,
- # which is what a 502 or 504 in front of it looks like from here.
- return json.dumps({
- "error": f"The video-generation gateway answered HTTP {response.status_code} with an unreadable body.",
- "transport_error": True,
- })
-
- if response.status_code >= 400:
- error = payload.get("error") if isinstance(payload.get("error"), dict) else {}
- message = error.get("message") or f"the gateway refused the request (HTTP {response.status_code})"
- out: dict = {"error": str(message)}
- if isinstance(error.get("details"), dict):
- out["details"] = error["details"]
- return json.dumps(out, ensure_ascii=False)
-
- guidance = payload.pop("guidance", None)
- return json.dumps(
- {"result": guidance or "Request accepted.", "details": payload},
- ensure_ascii=False,
- )
-
-
-# ---------------------------------------------------------------------------
-# Media delivery
-# ---------------------------------------------------------------------------
-
-# Every media field the gateway understands, and the media kind each accepts.
-# `input_image` and `input_images` are interchangeable server-side, so both
-# must be sanitized whatever the mode.
-_MEDIA_FIELDS = {
- "input_image": ("image",),
- "input_images": ("image",),
- "input_video": ("video",),
-}
-# The vendor takes at most ten keyframes. Checked here as well as server-side
-# so an over-long list is refused before it spends the caller's upload quota.
-_MAX_IMAGES = 10
-
-
-# One get_result call looks repeatedly rather than a fixed twice. The job
-# endpoint answers immediately — there is no long poll — so every second
-# between looks is a second a finished clip goes unnoticed, and many
-# short-spaced looks per call cut both that notice delay and the number of
-# times the model has to decide to keep waiting.
-#
-# Two bounds keep the loop inside the agent's per-tool ceiling. model_tools'
-# async bridge abandons a tool at 300s and reports it to the model as a bare
-# "TimeoutError:" — no job id, no sign the generation is still alive — which is
-# the worst answer this tool can give, so neither bound may approach it.
-# _CALL_BACKSTOP_SECONDS is the wall-clock guarantee over the whole handler;
-# _POLL_BUDGET_SECONDS stops new looks earlier still, and the difference
-# between them is what a clip finishing on the last look has to download in.
-_CALL_BACKSTOP_SECONDS = 240.0
-_POLL_BUDGET_SECONDS = 180.0
-# The gap between looks, and so the notice delay on a finished job. The
-# gateway's poll limiter allows 120 a minute per principal, and it only ever
-# has one generation of ours to answer for, so this cadence spends about a
-# tenth of what it permits.
-_POLL_GAP_SECONDS = 5.0
-# The budget is counted as it is spent — the waits and the time each look
-# actually takes — rather than read off a wall clock. A slow gateway therefore
-# costs looks instead of overrunning the call, and the loop stays testable
-# without a fake clock.
-#
-# Waits are taken in slices so they stay answerable. Nothing outside a tool can
-# end a call that has already started — the executor only checks for an
-# interrupt between tools — so a tool that blocks this long watches the flag
-# itself.
-_POLL_WAIT_SLICE_SECONDS = 1.0
-# A poll's own read timeout. It has to clear the gateway's server-side poll
-# budget, which bounds one status read at 45s across its retries and its
-# regional redirect hops: cutting a poll off before the server would give up
-# turns a slow-but-healthy read into a transport error, and an error ends the
-# loop. Still far below the submit path's patience, so a wedged poll cannot
-# quietly spend the whole call either.
-_POLL_READ_TIMEOUT_SECONDS = 60.0
-# How many looks in a row may fail to reach the gateway before the loop gives
-# up on the call. A blip costs a look rather than the whole remaining budget:
-# ending on the first one hands the model an error it can only answer by
-# polling again immediately, which is the burst this loop exists to prevent.
-# Bounded so a gateway that is genuinely down is reported promptly instead of
-# being retried for minutes.
-_MAX_CONSECUTIVE_TRANSPORT_ERRORS = 3
-
-# Mirrors the gateway's BFL statuses
-_TERMINAL_POLL_STATUSES = frozenset(
- {"Ready", "Error", "Request Moderated", "Content Moderated", "Task not found"}
-)
-
-
-def _poll_is_finished(raw: str) -> bool:
- """True when there is nothing to wait for: done, refused, or unreadable."""
- try:
- payload = json.loads(raw)
- except Exception:
- return True
- if not isinstance(payload, dict) or "error" in payload:
- # A refusal carries its own guidance (a limit, a dead job, a bad id),
- # and sleeping on it would only delay showing the model what to do.
- # The one exception is a throttle, which states a wait the loop can
- # absorb — the caller checks _retry_after_seconds before asking here.
- return True
- details = payload.get("details")
- status = details.get("status") if isinstance(details, dict) else None
- return not isinstance(status, str) or status in _TERMINAL_POLL_STATUSES
-
-
-def _retry_after_seconds(raw: str) -> Optional[float]:
- """How long the gateway asked us to wait, when a refusal is a throttle.
-
- A throttle is the one refusal worth absorbing here rather than handing
- back. Returning it ends the call, and the model it lands on has no clock —
- told to wait, it asks again immediately — so a rate limit answered that way
- produces a tighter loop than the one that tripped it. The gateway sends the
- wait as a number alongside the message, so there is nothing to parse out of
- prose.
- """
- try:
- payload = json.loads(raw)
- except Exception:
- return None
- if not isinstance(payload, dict) or "error" not in payload:
- return None
- details = payload.get("details")
- value = details.get("retryAfterSeconds") if isinstance(details, dict) else None
- if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
- return None
- return float(value)
-
-
-def _is_transport_error(raw: str) -> bool:
- """True when the gateway did not answer, as opposed to answering "no".
-
- Set by ``_call_gateway`` on the paths where nothing readable came back, so
- this reads a flag rather than matching on the text of a message.
- """
- try:
- payload = json.loads(raw)
- except Exception:
- return False
- return isinstance(payload, dict) and payload.get("transport_error") is True
-
-
-async def _wait_between_looks(seconds: float) -> bool:
- """Hold the call open until the next look; False if the user interrupted."""
- from tools.interrupt import is_interrupted
-
- remaining = seconds
- while remaining > 0:
- if is_interrupted():
- return False
- this_slice = min(_POLL_WAIT_SLICE_SECONDS, remaining)
- await asyncio.sleep(this_slice)
- remaining -= this_slice
- return True
-
-
-def _warm_nous_token() -> None:
- """Refresh the Nous token once, before any parallel upload needs it.
-
- ``read_nous_access_token`` takes no lock and, when a refresh fails, falls
- back to returning the stale cached token. Uploading in parallel therefore
- had every request discover the token was expiring at the same instant and
- fire its own refresh; the rotating refresh token means the first wins and
- the rest quietly send the stale bearer, which the gateway answers with 401.
- One warm-up call first puts a fresh token in the cache, so the fan-out all
- reads it instead of racing for it.
- """
- try:
- read_nous_access_token()
- except Exception as exc: # pragma: no cover — the real read retries below
- logger.debug("Nous token warm-up failed before parallel uploads: %s", exc)
-
-
-async def _prepare_media(args: dict, task_id: Optional[str]) -> dict:
- """Replace local paths with upload references in every media field.
-
- Deliberately covers all media fields rather than the one this mode
- expects. The gateway accepts `input_image` and `input_images`
- interchangeably, so a value left unsanitized in the "wrong" field still
- reaches the vendor — as a raw local path, which both fails the generation
- and discloses the user's directory layout to a third party.
- """
- prepared = dict(args or {})
- _warm_nous_token()
- for field, permitted in _MEDIA_FIELDS.items():
- value = prepared.get(field)
- if value is None:
- continue
- if isinstance(value, list):
- if len(value) > _MAX_IMAGES:
- raise ValueError(f"{field} takes at most {_MAX_IMAGES} images; you passed {len(value)}.")
- # Uploaded together rather than one after another: each entry is a
- # presign round trip plus a full-file PUT, and ten keyframes in
- # sequence took long enough that a submit looked hung.
- prepared[field] = list(
- await asyncio.gather(*(_deliver_media(entry, permitted, task_id) for entry in value))
- )
- else:
- prepared[field] = await _deliver_media(value, permitted, task_id)
- return prepared
-
-
-def _without_media(args: dict) -> dict:
- """Drop media fields entirely — for the mode that takes none.
-
- The gateway ignores them for text-to-video, so stripping here matches its
- behaviour while avoiding an upload the caller never needed.
- """
- return {k: v for k, v in dict(args or {}).items() if k not in _MEDIA_FIELDS}
-
-
-async def _deliver_media(value, permitted: tuple, task_id: Optional[str]):
- """Replace a local path with a ``nous-upload:`` reference; pass URLs through.
-
- Raises ``ValueError`` with a model-readable sentence when the file cannot
- be read or uploaded — the caller turns that into the tool's error payload.
- """
- if not isinstance(value, str) or not _looks_like_local_path(value):
- return value
-
- from tools.image_source import ImageResolutionError, ResolveContext, resolve_image_source
-
- try:
- resolved = await resolve_image_source(value, ResolveContext(task_id=task_id), permitted=permitted)
- except ImageResolutionError as exc:
- raise ValueError(f"Could not read {_display_path(value)}: {exc}") from exc
-
- endpoints = _endpoints()
- uploader = None
- if endpoints is not None:
- uploader = build_managed_media_uploader(endpoints["base_url"], endpoints["upload_path"])
- if uploader is None:
- raise ValueError("Local file uploads are not available in this build; pass a URL instead.")
-
- try:
- return await uploader(resolved.data, resolved.mime)
- except Exception as exc:
- raise ValueError(f"Could not upload {_display_path(value)}: {exc}") from exc
-
-
-# ---------------------------------------------------------------------------
-# Saving the finished clip
-# ---------------------------------------------------------------------------
-
-# Generous: a 50MB clip over a slow link. Bounded per call by what is left of
-# the backstop, so this is a ceiling rather than the figure actually used.
-_DOWNLOAD_READ_TIMEOUT_SECONDS = 300.0
-_DOWNLOAD_CONNECT_TIMEOUT_SECONDS = 15.0
-# Kept clear of the backstop so the download's own timeout fires first: that
-# way a stalled save is reported as one, instead of being cancelled mid-write
-# with the call's answer lost.
-_DOWNLOAD_GRACE_SECONDS = 5.0
-# A rejection page is a few hundred bytes of XML; a clip is megabytes. Anything
-# smaller than this is not the video, whatever the HTTP status said.
-_MIN_PLAUSIBLE_VIDEO_BYTES = 64 * 1024
-# Enough collision suffixes to be useful, few enough to fail fast if something
-# is generating files in a loop.
-_MAX_FILENAME_ATTEMPTS = 50
-
-
-def _download_read_timeout(started: float) -> float:
- """What is left of the call for a download, never more than the ceiling.
-
- Without this the download's own generous timeout outlives the agent's
- per-tool ceiling, and the "saving failed, poll again to retry" answer below
- is never reached: the bridge kills the call first and the model is told
- only "TimeoutError", with no indication the clip exists and is one poll
- away.
-
- Must not invent time past what remains: clamping upward used to schedule a
- download the outer ``asyncio.wait_for`` then cancelled, answering with a
- false ``_still_generating`` while the job was already Ready.
- """
- left = _CALL_BACKSTOP_SECONDS - (time.monotonic() - started) - _DOWNLOAD_GRACE_SECONDS
- return max(0.0, min(_DOWNLOAD_READ_TIMEOUT_SECONDS, left))
-
-
-async def _save_if_ready(raw: str, save_to, started: float) -> str:
- """Download a finished clip and swap the signed URL for a local path.
-
- The URL is handled here rather than by the model on purpose. It is long and
- percent-encoded, and re-keying it into a shell command dropped characters
- often enough to be the main failure mode of this tool — a corrupted
- signature is rejected, but `curl` still writes the rejection body to the
- output file and exits 0, so it read as success. Passing the exact string
- from this response removes the transcription step entirely.
-
- It also keeps a bearer credential out of the transcript: the signed URL
- grants the clip to anyone holding it for the next 15-60 minutes, and
- returning it put it in the model's context and the saved conversation. The
- gateway already scrubs presigned URLs for *input* media for exactly this
- reason; this makes the output side match.
- """
- try:
- payload = json.loads(raw)
- except Exception:
- return raw
- if not isinstance(payload, dict):
- return raw
-
- details = payload.get("details")
- if not isinstance(details, dict) or details.get("status") != "Ready":
- return raw
-
- result = details.get("result")
- url = result.get("sample") if isinstance(result, dict) else None
- if not isinstance(url, str) or not url.strip():
- return raw
-
- # Dropped whether or not the save succeeds. A retry re-polls, which mints a
- # fresh URL, so nothing is lost by not handing this one to the model.
- result.pop("sample", None)
-
- try:
- target, size = await _download_video(url.strip(), save_to, started)
- except Exception as exc:
- payload["result"] = (
- f"The clip finished but saving it failed: {type(exc).__name__}: {exc}. "
- "Poll this job again to retry the download; the job itself is unaffected."
- )
- return json.dumps(payload, ensure_ascii=False)
-
- details["saved_path"] = str(target)
- details["saved_bytes"] = size
- payload["result"] = _delivery_lead_in(target) + str(payload.get("result") or "")
- return json.dumps(payload, ensure_ascii=False)
-
-
-def _delivery_lead_in(target) -> str:
- """Opens the result text, ahead of the gateway's own delivery guidance.
-
- On a messaging platform the tag is spelled out rather than described. The
- model has to reproduce this path exactly or the file is not sent, and the
- reply is published either way — the tag is stripped from the text whether
- or not it named a real file, so a wrong path reads to the user as a
- message that simply forgot the attachment. Handing over the finished line
- removes the step where that goes wrong; only this side knows the path.
- """
- if _delivers_as_an_attachment():
- return (
- f"Saved to {target}. To deliver it, copy the next line into your reply exactly as "
- f"written, alone on its own line, with nothing added around it:\n"
- f"MEDIA:{target}\n"
- )
- return f"Saved to {target}. "
-
-
-async def _download_video(url: str, save_to, started: float) -> tuple:
- """Stream the clip to disk, returning (path, bytes).
-
- SSRF-guarded, for the same reason the upload PUT is: this URL comes from
- the vendor by way of the gateway, and it is fetched from the user's own
- machine. Real result URLs are public CDN objects, which the guard allows.
- """
- import httpx
-
- from tools.url_safety import create_ssrf_safe_async_client
-
- target = _resolve_destination(save_to, _filename_from_url(url))
- # Written under a .part name and renamed only once it is complete and
- # plausible, so a failed download can never leave something that looks like
- # a playable file behind.
- partial = target.with_name(target.name + ".part")
- timeout = httpx.Timeout(_DOWNLOAD_CONNECT_TIMEOUT_SECONDS, read=_download_read_timeout(started))
-
- try:
- async with create_ssrf_safe_async_client(timeout=timeout, follow_redirects=True) as client:
- async with client.stream("GET", url) as response:
- response.raise_for_status()
- with partial.open("wb") as handle:
- async for chunk in response.aiter_bytes():
- handle.write(chunk)
-
- size = partial.stat().st_size
- if size < _MIN_PLAUSIBLE_VIDEO_BYTES:
- raise ValueError(f"the download returned only {size} bytes, which is not a video")
- partial.replace(target)
- except BaseException:
- partial.unlink(missing_ok=True)
- raise
-
- return target, size
-
-
-def _filename_from_url(url: str) -> str:
- from pathlib import PurePosixPath
- from urllib.parse import unquote, urlsplit
-
- name = PurePosixPath(unquote(urlsplit(url).path)).name
- # The path segment is vendor-controlled, so keep only a plain filename.
- name = re.sub(r"[^A-Za-z0-9._-]", "_", name).lstrip(".")[:120]
- return name or "flux3-video.mp4"
-
-
-def _delivers_as_an_attachment() -> bool:
- """True on a surface where the clip is received rather than opened off disk.
-
- Deferred to the shared classifier so this tool cannot drift from the rest
- of the codebase about what counts as a chat channel. It matters here that
- the API server and webhooks are *not* one: they carry a platform value but
- no attachment channel, and neither strips an unfulfilled MEDIA: tag out of
- the reply, so treating them as messaging puts the literal tag in front of
- the caller.
- """
- try:
- from gateway.session_context import session_is_messaging_surface
-
- return session_is_messaging_surface()
- except Exception:
- return False
-
-
-def _default_directory():
- """Where a clip lands when the caller named no location.
-
- On a messaging platform the user has no filesystem — the only way they
- ever see the clip is as an attachment — so it goes to the gateway's own
- video cache, which is an unconditionally allowed delivery root. Downloads
- is not: an operator running HERMES_MEDIA_DELIVERY_STRICT=1 delivers only
- from the cache roots, so a clip saved to Downloads there is dropped on the
- way out and the user is shown a reply with nothing attached.
- """
- from pathlib import Path
-
- if _delivers_as_an_attachment():
- try:
- from hermes_constants import get_hermes_dir
-
- return get_hermes_dir("cache/videos", "video_cache")
- except Exception:
- logger.debug("Could not resolve the video cache dir; using Downloads", exc_info=True)
- downloads = Path.home() / "Downloads"
- return downloads if downloads.is_dir() else Path.cwd()
-
-
-def _resolve_destination(save_to, filename: str):
- """Where to write, honouring an explicit request and never overwriting."""
- from pathlib import Path
-
- if isinstance(save_to, str) and save_to.strip():
- requested = Path(save_to.strip()).expanduser()
- if requested.is_dir() or save_to.rstrip().endswith(("/", "\\")):
- directory, name = requested, filename
- else:
- directory, name = requested.parent, requested.name
- else:
- directory, name = _default_directory(), filename
-
- directory.mkdir(parents=True, exist_ok=True)
- return _free_path(directory / name)
-
-
-def _free_path(candidate):
- """`name.mp4` -> `name-2.mp4` -> `name-3.mp4` … so nothing is clobbered."""
- if not candidate.exists():
- return candidate
- for suffix in range(2, _MAX_FILENAME_ATTEMPTS + 2):
- sibling = candidate.with_name(f"{candidate.stem}-{suffix}{candidate.suffix}")
- if not sibling.exists():
- return sibling
- raise ValueError(f"could not find a free filename next to {candidate}")
-
-
-# ---------------------------------------------------------------------------
-# Handlers
-# ---------------------------------------------------------------------------
-
-def _error(message: str) -> str:
- return json.dumps({"error": message}, ensure_ascii=False)
-
-
-def _submit_args(mode: str, args: dict) -> dict:
- """The wire body: the model's arguments, minus Nones, plus our mode.
-
- Arguments pass through as the model gave them; the gateway owns validation
- and the translation onto the vendor's own fields.
- """
- body = {k: v for k, v in dict(args or {}).items() if v is not None}
- body["mode"] = mode
- return body
-
-
-async def _submit(mode: str, args: dict) -> str:
- endpoints = _endpoints()
- if endpoints is None:
- return _error("BFL video generation is not available in this build.")
- return await _call_gateway("POST", f"{endpoints['base_url']}/generations", _submit_args(mode, args))
-
-
-async def _handle_text_to_video(args: dict, **kwargs) -> str:
- return await _submit("text_to_video", _without_media(args))
-
-
-async def _handle_image_to_video(args: dict, **kwargs) -> str:
- try:
- prepared = await _prepare_media(args, kwargs.get("task_id"))
- except ValueError as exc:
- return _error(str(exc))
- return await _submit("image_to_video", prepared)
-
-
-async def _handle_keyframes_to_video(args: dict, **kwargs) -> str:
- images = (args or {}).get("input_images")
- if not isinstance(images, list) or not images:
- return _error("input_images must be a non-empty list of 1-10 images (local paths or URLs).")
- try:
- prepared = await _prepare_media(args, kwargs.get("task_id"))
- except ValueError as exc:
- return _error(str(exc))
- return await _submit("keyframes_to_video", prepared)
-
-
-async def _handle_video_continuation(args: dict, **kwargs) -> str:
- try:
- prepared = await _prepare_media(args, kwargs.get("task_id"))
- except ValueError as exc:
- return _error(str(exc))
- return await _submit("video_continuation", prepared)
-
-
-def _still_generating(job_id: str) -> str:
- """The backstop's answer: an ordinary "call again", never a raised timeout."""
- return json.dumps(
- {
- "result": (
- "Still generating. This call reached its own time limit, which the job is "
- f"unaffected by — call bfl_flux3_get_result again with id={job_id} to keep "
- "waiting."
- ),
- "details": {"id": job_id, "status": "Generating"},
- },
- ensure_ascii=False,
- )
-
-
-async def _poll_until_done(url: str, save_to, started: float) -> str:
- """Look until the job settles, the budget runs out, or the user stops.
-
- The waiting is absorbed here rather than asked of the model. A model has no
- clock: told to wait it emits "I'll check back in a minute" and its next
- action lands immediately, so guidance produced a burst of polls rather than
- a paced one. Waiting inside the call cannot be skipped, needs no shell, and
- works the same on every platform.
- """
- spent = 0.0
- unanswered = 0
- while True:
- look_started = time.monotonic()
- raw = await _call_gateway("GET", url, read_timeout=_POLL_READ_TIMEOUT_SECONDS)
- spent += time.monotonic() - look_started
-
- if _is_transport_error(raw):
- # The job is upstream and unaffected by our failure to ask about
- # it, so a blip costs this look and the loop tries again.
- unanswered += 1
- if unanswered >= _MAX_CONSECUTIVE_TRANSPORT_ERRORS:
- return raw
- gap = _POLL_GAP_SECONDS
- else:
- unanswered = 0
- throttled_for = _retry_after_seconds(raw)
- if throttled_for is None and _poll_is_finished(raw):
- return await _save_if_ready(raw, save_to, started)
- # Never faster than our own cadence, however short a wait the
- # gateway names: its number is a floor on politeness, not a licence
- # to hammer.
- gap = _POLL_GAP_SECONDS if throttled_for is None else max(throttled_for, _POLL_GAP_SECONDS)
-
- if gap <= 0 or spent + gap >= _POLL_BUDGET_SECONDS:
- # Out of budget. A still-generating status carries the gateway's own
- # "call again"; a throttle we could not outwait carries its wait.
- return raw
- if not await _wait_between_looks(gap):
- # Interrupted mid-wait: hand back the status we already have rather
- # than spending a round trip the user has just asked us to stop for.
- return raw
- spent += gap
-
-
-async def _handle_get_result(args: dict, **kwargs) -> str:
- job_id = (args or {}).get("id")
- if not isinstance(job_id, str) or not job_id.strip():
- return _error("id is required: the job id returned by the generate tool.")
- endpoints = _endpoints()
- if endpoints is None:
- return _error("BFL video generation is not available in this build.")
- from urllib.parse import quote
-
- job_id = job_id.strip()
- url = f"{endpoints['base_url']}/generations/{quote(job_id, safe='')}"
- save_to = (args or {}).get("save_to")
- started = time.monotonic()
-
- # The loop stops itself once its budget is spent, but a look already in
- # flight still runs to completion, and a download follows it. This is the
- # wall-clock guarantee over all of that: whatever stalls inside, the model
- # is answered from here rather than by the async bridge, whose own timeout
- # arrives as a bare "TimeoutError:".
- try:
- return await asyncio.wait_for(
- _poll_until_done(url, save_to, started), timeout=_CALL_BACKSTOP_SECONDS
- )
- except asyncio.TimeoutError:
- return _still_generating(job_id)
-
-
-async def _handle_prompting_guide(args: dict, **kwargs) -> str:
- return FLUX3_PROMPTING_GUIDE
-
-
-# ---------------------------------------------------------------------------
-# Gating
-# ---------------------------------------------------------------------------
-
-def _has_nous_credential() -> bool:
- """True when a Nous bearer is on hand, without spending a refresh to learn it.
-
- Two lookups, because the transport itself has two.
- ``peek_nous_access_token`` covers the env override and the active store's
- cached token. A profile that was never logged into separately has neither,
- and reads the credential from the global-root ``auth.json`` — the same
- fallback ``resolve_nous_access_token`` takes when the transport refreshes.
- Probing only the first would hide the tools from a profile whose calls
- would have gone through perfectly well.
-
- Neither lookup validates or refreshes the token: an expired credential is
- the gateway's 401 to report, and that answer already asks for a sign-in.
- """
- if peek_nous_access_token():
- return True
- try:
- from hermes_cli.auth import get_provider_auth_state
-
- state = get_provider_auth_state("nous") or {}
- except Exception:
- return False
- token = state.get("access_token")
- return isinstance(token, str) and bool(token.strip())
-
-
-def check_bfl_requirements() -> bool:
- """Visible to anyone signed in to Nous; the gateway rules on the rest.
-
- No entitlement check. What an account may generate — plan, credits, per
- account limits — is the gateway's decision, and it refuses with a reason
- written for the model to act on; deciding it a second time here can only
- disagree with the server and hide the tools from someone entitled to them.
-
- A sign-in is still required, because the gateway takes a Nous bearer and
- nothing else: with no credential every call could only ever answer "sign
- in", so the six schemas would be pure cost on every API call.
-
- Stays a pair of file reads — no portal probe, no OAuth refresh. Behind the
- registry's 30s cache this still runs on every CLI start, gateway session
- and cron tick.
- """
- try:
- if _endpoints() is None:
- return False
- return _has_nous_credential()
- except Exception:
- return False
-
-
-# ---------------------------------------------------------------------------
-# Pinned schemas
-# ---------------------------------------------------------------------------
-
-_ASPECT_RATIOS = ["auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16", "9:21"]
-_RESOLUTIONS = ["720p"]
-
-_GUIDE_POINTER = "Read bfl_flux3_prompting_guide before your first generation. "
-_MEDIA_SENTENCE = (
- "Media fields accept a local file path (uploaded automatically to Nous-managed temporary "
- "storage and deleted when the generation finishes) or a URL. "
-)
-_OVERRIDE_SENTENCE = "All guidance is defaults: explicit user instructions override it."
-
-
-def _shared_submit_properties() -> dict:
- return {
- "prompt": {
- "type": "string",
- "minLength": 1,
- "description": (
- "Generation brief in plain prose (it is interpreted and expanded by a reasoning "
- "harness). Order it subject, distinguishing visual specifics, action, camera, "
- "lighting, environment, audio, style. Audio is generated by default — say "
- '"no music" if unwanted.'
- ),
- },
- "aspect_ratio": {
- "type": "string",
- "enum": list(_ASPECT_RATIOS),
- "default": "auto",
- "description": 'Output aspect ratio. "auto" lets the model choose.',
- },
- "duration": {
- "oneOf": [
- {"type": "integer", "minimum": 5, "maximum": 20},
- {"type": "string", "const": "auto"},
- ],
- "default": "auto",
- "description": 'Clip duration in whole seconds (5-20), or "auto".',
- },
- "resolution": {
- "type": "string",
- "enum": list(_RESOLUTIONS),
- "default": "720p",
- "description": "Output resolution bin.",
- },
- "generate_audio": {
- "type": "boolean",
- "default": True,
- "description": "Generate synchronized audio.",
- },
- "grounding": {
- "type": "boolean",
- "default": True,
- "description": "Allow a short research pass before generation.",
- },
- "seed": {
- "type": "integer",
- "minimum": 0,
- "maximum": 4294967295,
- "description": "Optional reproducibility seed.",
- },
- "version": {
- "type": "string",
- "description": 'Model version pin. Defaults to "latest".',
- },
- }
-
-
-TEXT_TO_VIDEO_SCHEMA = {
- "name": "bfl_flux3_text_to_video",
- "description": (
- _GUIDE_POINTER
- + "FLUX 3 text-to-video: generates a clip (with audio) from the prompt alone. Nothing but "
- "the prompt anchors the subject here, so research anything with a real, checkable "
- "appearance before writing it — whatever you leave unspecified is filled in for you. "
- "Generation takes several minutes: this returns a job id immediately; poll "
- "bfl_flux3_get_result. "
- + _OVERRIDE_SENTENCE
- ),
- "parameters": {
- "type": "object",
- "properties": _shared_submit_properties(),
- "required": ["prompt"],
- "additionalProperties": False,
- },
-}
-
-IMAGE_TO_VIDEO_SCHEMA = {
- "name": "bfl_flux3_image_to_video",
- "description": (
- _GUIDE_POINTER
- + "FLUX 3 image-to-video: animates one image as the literal opening frame — those pixels "
- "are frame 0 and the clip moves from there. "
- + _MEDIA_SENTENCE
- + "Returns a job id; poll bfl_flux3_get_result. "
- + _OVERRIDE_SENTENCE
- ),
- "parameters": {
- "type": "object",
- "properties": {
- **_shared_submit_properties(),
- "input_image": {
- "type": "string",
- "minLength": 1,
- "description": "Exactly one opening-frame image: a local file path or a URL (PNG/JPEG/WebP, up to 10MB).",
- },
- },
- "required": ["prompt", "input_image"],
- "additionalProperties": False,
- },
-}
-
-KEYFRAMES_TO_VIDEO_SCHEMA = {
- "name": "bfl_flux3_keyframes_to_video",
- "description": (
- _GUIDE_POINTER
- + "FLUX 3 keyframe video: a storyboard of 1-10 images pinned at chosen frame positions "
- "(24fps). Name the subject and describe the motion that carries it between the pins, and "
- "keep the subject consistent across every pinned image. "
- + _MEDIA_SENTENCE
- + "Returns a job id; poll bfl_flux3_get_result. "
- + _OVERRIDE_SENTENCE
- ),
- "parameters": {
- "type": "object",
- "properties": {
- **_shared_submit_properties(),
- "input_images": {
- "type": "array",
- "items": {"type": "string", "minLength": 1},
- "minItems": 1,
- "maxItems": 10,
- "description": "1-10 keyframe images: local file paths or URLs (PNG/JPEG/WebP, up to 10MB each).",
- },
- "keyframe_indices": {
- "type": "array",
- "items": {"type": "integer", "minimum": 0, "maximum": 480},
- "minItems": 1,
- "maxItems": 10,
- "description": (
- "One unique non-negative frame index per image (24fps). Each must be at most "
- 'duration×24, so set an explicit duration rather than "auto" whenever you pin '
- 'indices — "auto" resolves to 5, 10, 15 or 20 seconds and an index past the '
- "length it picks is rejected."
- ),
- },
- },
- "required": ["prompt", "input_images", "keyframe_indices"],
- "additionalProperties": False,
- },
-}
-
-VIDEO_CONTINUATION_SCHEMA = {
- "name": "bfl_flux3_video_continuation",
- "description": (
- _GUIDE_POINTER
- + "FLUX 3 video continuation: the new generation picks up from the input clip's final "
- 'frames. Open the prompt with "Continue this video from its final frames:", re-establish '
- "the subject and the moment it ended on, then describe what happens next. input_video "
- "must be an mp4 of at most 50MB and 15 seconds, and the generated segment tops out at 15s "
- "too — chain a second continuation for a longer sequence. duration is the "
- "new segment only. "
- + _MEDIA_SENTENCE
- + "Returns a job id; poll bfl_flux3_get_result. "
- + _OVERRIDE_SENTENCE
- ),
- "parameters": {
- "type": "object",
- "properties": {
- **_shared_submit_properties(),
- "input_video": {
- "type": "string",
- "minLength": 1,
- "description": "The clip to continue: a local file path or a URL. mp4 only, at most 50MB and 15 seconds.",
- },
- },
- "required": ["prompt", "input_video"],
- "additionalProperties": False,
- },
-}
-
-GET_RESULT_SCHEMA = {
- "name": "bfl_flux3_get_result",
- "description": (
- "Poll a FLUX 3 video job by the job id a generate tool returned. Generation takes minutes "
- "and a long Generating phase is normal. This call waits for you while the job runs, so it "
- "may run for several minutes; if it returns still generating, just call it again. Do not "
- "sleep between calls. "
- "On Ready the clip is downloaded for you and the response gives its local path; your only "
- "remaining step is to deliver that file as the response describes."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string",
- "minLength": 1,
- "description": "Job id from a previous bfl_flux3_* generate call.",
- },
- "save_to": {
- "type": "string",
- "description": (
- "Where to save the finished clip: a directory or a full file path. Set this "
- "only when the user asked for a particular location; the default is "
- "~/Downloads. An existing file is never overwritten."
- ),
- },
- },
- "required": ["id"],
- "additionalProperties": False,
- },
-}
-
-PROMPTING_GUIDE_SCHEMA = {
- "name": "bfl_flux3_prompting_guide",
- "description": (
- "Read this before your first FLUX 3 generation. The prompting and grounding guide: how "
- "to research a subject so it renders as itself, how to assemble a prompt, which generate "
- "tool fits, and how to save and deliver the finished clip. Takes no arguments and spends "
- "no generation budget."
- ),
- "parameters": {"type": "object", "properties": {}, "additionalProperties": False},
-}
-
-
-# ---------------------------------------------------------------------------
-# Pinned prompting guide (methodology only — policy numbers such as waits and
-# limits arrive live in the gateway's tool responses, so they cannot drift)
-# ---------------------------------------------------------------------------
-
-FLUX3_PROMPTING_GUIDE = """# FLUX 3 video generation — how to get the best results
-
-Everything here is guidance, not policy: the user's explicit instructions
-always win. If they say skip the research, save somewhere specific, or deliver
-differently — do it their way without arguing. Only the server's own validation
-and limits are non-negotiable.
-
-Start from the user's own wording. The prompt is rewritten by a reasoning
-harness before anything is generated, so restyling it yourself just stacks a
-second rewrite on top and gives their intent another chance to drift. There are
-two reasons to add anything: grounding facts for a subject with a real,
-checkable appearance, and the behaviours below, which they had no way to know
-about. Absent those, send what they wrote.
-
-## Grounding
-
-Grounding is your job, and it is the highest-leverage step in the workflow.
-What you specify is preserved; what you leave out is filled in for you. So
-when a subject has a real, checkable appearance, research it first and put
-what you found into the prompt — that is what makes the result yours rather
-than an approximation of it.
-
-Ground whenever someone who knows the subject could watch the clip and say
-"that's not what that is": a named person or place, a landmark, a particular
-vehicle or machine, anything technical, anything culturally specific, or a
-period setting. Skip it for generics ("a dog on a beach") — there is no fact
-to get wrong.
-
-To ground: search for VISUAL references, where three good photographs beat any
-amount of prose. If you can analyze images, analyze what you find. Then put
-only what a camera could see into the prompt: silhouette and proportion,
-materials and finish, specific colours, distinctive details, era-correct
-context.
-
-## How this model behaves
-
-The prompt is read by a reasoning harness rather than a tag encoder, so keyword
-tricks and word order do nothing. Write plain prose at whatever length the
-brief deserves; a single line is a valid prompt.
-
-Audio is generated by default, whether or not you mention it, so leaving it out
-gets you invented sound rather than silence. Name the ambient sound, the music
-and any speech separately — each lands as its own layer — and say "no music"
-when you do not want it.
-
-A quoted line becomes speech only if a speaker is visible on camera. Without
-one it tends to render as burned-in text instead, so quote the line, describe
-the speaker, and add "no on-screen text, no subtitles".
-
-Multi-shot sequences work inside a single generation: "SHOT ONE ... HARD CUT.
-SHOT TWO ..." produces real cuts, and "one continuous unbroken shot" gets an
-uncut take. Consecutive shots have to contrast in scale, location or colour or
-the cut will not read as one — near-identical coverage blends back into a
-continuous take.
-
-## Choosing a tool
-
-- No input media -> bfl_flux3_text_to_video.
-- Animate one image as the literal opening frame ->
- bfl_flux3_image_to_video (those pixels are frame 0, and the clip moves from
- there). Name the subject and its distinguishing specifics here as you would
- anywhere else: only frame 0 is pinned, every frame after it is generated,
- and what you leave out is the model's call rather than yours.
-- Several images pinned at chosen moments -> bfl_flux3_keyframes_to_video
- (name the subject and describe the motion that carries it between the pins;
- keep it consistent across every pin, since a mismatch becomes a visible
- morph mid-clip). Pin exact indices and you want an explicit duration too —
- every index must fall within duration×24.
-- Keep going from where a clip ends, or chain segments ->
- bfl_flux3_video_continuation. Open with "Continue this video from its final
- frames:", re-establish the subject and the moment the clip ended on, then
- describe what happens next; duration is the new segment only, so plan
- segments of 15 seconds or less to feed outputs back in.
-
-## Media inputs
-
-Pass local file paths directly — never hand-encode file contents into an argument.
-URLs also work. Limits per file:
-images 10MB (PNG/JPEG/WebP), video one mp4 of at most 50MB and 15 seconds.
-Do not pre-shrink files to fit imagined caps; oversized pixel dimensions are
-auto-downscaled and output tops out at 720p.
-
-## Workflow
-
-Submit returns a job id immediately — the video does not exist yet. Poll
-bfl_flux3_get_result with that id; generation takes several minutes and a long
-Generating phase is normal, not a stall. Nothing reaches disk before the job is
-Ready, so checking folders mid-run tells you nothing.
-
-The waiting is not yours to do. bfl_flux3_get_result takes the pause itself
-while a job is still running, so one call can occupy several minutes and comes
-back within seconds of the job finishing. If it returns still generating, just
-call it again — no sleeping, no interval to judge, nothing to time.
-
-A job survives client restarts: re-poll the same id rather than resubmitting,
-which would only spend your budgets on duplicate work.
-
-## Save and deliver
-
-bfl_flux3_get_result saves the clip itself and returns saved_path. The download
-is not yours to do and no URL is handed to you to fetch. Pass save_to only when
-the user named a location; otherwise it lands in ~/Downloads, and an existing
-file is never overwritten. If saving fails the response says so — poll the same
-job again to retry, which is safe and spends no generation budget.
-
-Then deliver that file so the clip plays inline. Which markup plays inline is the
-host's decision, so check your system prompt or platform instructions and use
-exactly the form they give; the common ones are a MEDIA: tag alone on its own
-line and a markdown embed. Two things break it. Write the real absolute path,
-with ~ expanded. And keep the markup plain: wrapping it in bold, backticks or a
-code fence, or rewriting it as a [link](path), turns an inline player into
-literal text or a click-target. That is the most common way this step fails,
-and it reads as success because the filename is on screen. Where the
-instructions call for no delivery markup, or the host has no such mechanism,
-follow them and state the absolute path in plain text.
-
-Report what you did rather than what the job says it did: the echoed prompt
-field describes intent and often overstates what the render preserved.
-"""
-
-
-# ---------------------------------------------------------------------------
-# Registration (auto-discovered: top-level registry.register calls)
-# ---------------------------------------------------------------------------
-
-registry.register(
- name="bfl_flux3_text_to_video",
- toolset=_TOOLSET,
- schema=TEXT_TO_VIDEO_SCHEMA,
- handler=_handle_text_to_video,
- check_fn=check_bfl_requirements,
- requires_env=[],
- is_async=True,
- emoji="🎬",
-)
-
-registry.register(
- name="bfl_flux3_image_to_video",
- toolset=_TOOLSET,
- schema=IMAGE_TO_VIDEO_SCHEMA,
- handler=_handle_image_to_video,
- check_fn=check_bfl_requirements,
- requires_env=[],
- is_async=True,
- emoji="🎬",
-)
-
-registry.register(
- name="bfl_flux3_keyframes_to_video",
- toolset=_TOOLSET,
- schema=KEYFRAMES_TO_VIDEO_SCHEMA,
- handler=_handle_keyframes_to_video,
- check_fn=check_bfl_requirements,
- requires_env=[],
- is_async=True,
- emoji="🎬",
-)
-
-registry.register(
- name="bfl_flux3_video_continuation",
- toolset=_TOOLSET,
- schema=VIDEO_CONTINUATION_SCHEMA,
- handler=_handle_video_continuation,
- check_fn=check_bfl_requirements,
- requires_env=[],
- is_async=True,
- emoji="🎬",
-)
-
-registry.register(
- name="bfl_flux3_get_result",
- toolset=_TOOLSET,
- schema=GET_RESULT_SCHEMA,
- handler=_handle_get_result,
- check_fn=check_bfl_requirements,
- requires_env=[],
- is_async=True,
- emoji="🎬",
-)
-
-registry.register(
- name="bfl_flux3_prompting_guide",
- toolset=_TOOLSET,
- schema=PROMPTING_GUIDE_SCHEMA,
- handler=_handle_prompting_guide,
- check_fn=check_bfl_requirements,
- requires_env=[],
- is_async=True,
- emoji="📖",
-)
diff --git a/toolsets.py b/toolsets.py
index 23eacf088af..bab352a0bdb 100644
--- a/toolsets.py
+++ b/toolsets.py
@@ -44,10 +44,6 @@ _HERMES_CORE_TOOLS = [
"read_file", "write_file", "patch", "search_files",
# Vision + image generation
"vision_analyze", "image_generate",
- # BFL FLUX 3 video generation
- "bfl_flux3_text_to_video", "bfl_flux3_image_to_video",
- "bfl_flux3_keyframes_to_video", "bfl_flux3_video_continuation",
- "bfl_flux3_get_result", "bfl_flux3_prompting_guide",
# Skills
"skills_list", "skill_view", "skill_manage",
# Browser automation
@@ -161,25 +157,6 @@ TOOLSETS = {
"includes": []
},
- "bfl": {
- "description": (
- "Black Forest Labs FLUX 3 video generation through the Nous tool "
- "gateway: per-mode submit tools (text, image, keyframes, "
- "continuation), a poll tool, and a prompting guide. Generations "
- "take minutes, so submit returns a job id and the model polls for "
- "the result."
- ),
- "tools": [
- "bfl_flux3_text_to_video",
- "bfl_flux3_image_to_video",
- "bfl_flux3_keyframes_to_video",
- "bfl_flux3_video_continuation",
- "bfl_flux3_get_result",
- "bfl_flux3_prompting_guide",
- ],
- "includes": []
- },
-
"computer_use": {
"description": (
"Background desktop control via cua-driver (macOS/Windows/Linux) — "
@@ -469,10 +446,6 @@ TOOLSETS = {
"read_file", "write_file", "patch", "search_files",
# Vision + image generation
"vision_analyze", "image_generate",
- # BFL FLUX 3 video generation
- "bfl_flux3_text_to_video", "bfl_flux3_image_to_video",
- "bfl_flux3_keyframes_to_video", "bfl_flux3_video_continuation",
- "bfl_flux3_get_result", "bfl_flux3_prompting_guide",
# Skills
"skills_list", "skill_view", "skill_manage",
# Browser automation