Files
devplacepy/devplacepy/services/openai_gateway/muse_code.py
T
retoorandClaude Sonnet 5.5 bc11475f29 Send per-app provider attribution titles from one gateway app registry
Add openai_gateway/apps.py as the single list of internal gateway apps and
send X-OpenRouter-Title (plus legacy X-Title and HTTP-Referer) per app to
every upstream. Label the Devii agent, bots, modifier, quiz grading, SEO
metadata, community and sync callers. Shorten two app references that
exceeded the 30 character limit and were recorded as default.
Also includes the pending Muse Code, route health and Responses work.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 18:45:09 +01:00

258 lines
8.2 KiB
Python

# retoor <retoor@molodetz.nl>
from __future__ import annotations
import os
import platform
from devplacepy.utils.text import generate_uid
MUSE_CLIENT_VERSION = os.environ.get("MUSE_CLIENT_VERSION", "1.4.14")
MUSE_CLIENT_BUILD = os.environ.get(
"MUSE_CLIENT_BUILD", "dec7d7497fecdad135ec5835a8161dbc92e55b58"
)
MUSE_CLIENT_SURFACE = os.environ.get("MUSE_CLIENT_SURFACE", "exec")
MUSE_CONTRIBUTOR_MODE = os.environ.get("MUSE_CONTRIBUTOR_MODE", "1")
_OS_NAMES = {"darwin": "macos", "linux": "linux", "windows": "windows"}
_ARCH_NAMES = {
"arm64": "aarch64",
"aarch64": "aarch64",
"x86_64": "x86_64",
"amd64": "x86_64",
}
def _muse_platform() -> str:
system = _OS_NAMES.get(platform.system().lower(), "linux")
arch = _ARCH_NAMES.get(platform.machine().lower(), "x86_64")
return f"{system}-{arch}"
def _muse_user_agent() -> str:
override = os.environ.get("MUSE_CLIENT_USER_AGENT", "").strip()
if override:
return override
return (
f"muse-build/{MUSE_CLIENT_VERSION} (non-interactive; "
f"{_muse_platform()}; build {MUSE_CLIENT_BUILD})"
)
# Every one of these trips api.meta.ai's client gate with 403
# client_attestation_denied when declared as a tools[] function name
# (measured 2026-10-30, all 20 deny, near-misses pass). Text, history,
# params, and descriptions are not scanned - only exact tools[].name.
MUSE_RESERVED_TOOL_NAMES = frozenset(
{
"workflow",
"read_file",
"search",
"write_file",
"edit_file",
"read_memory",
"add_memory",
"edit_memory",
"web_search",
"bash",
"bash_input",
"cron_create",
"cron_delete",
"cron_list",
"get_goal",
"create_goal",
"update_goal",
"report_progress",
"read_skill",
"write_todos",
}
)
TOOL_ALIAS_PREFIX = "ext_"
META_UPSTREAM_HOST = "api.meta.ai"
def is_meta_upstream(url) -> bool:
return META_UPSTREAM_HOST in (url or "")
def _alias_for(name: str, taken: set) -> str:
alias = TOOL_ALIAS_PREFIX + name
while alias in taken:
alias = TOOL_ALIAS_PREFIX + alias
taken.add(alias)
return alias
def _declared_names(payload: dict) -> list:
names = []
for tool in payload.get("tools") or []:
if not isinstance(tool, dict):
continue
if tool.get("type") == "function":
name = (tool.get("function") or {}).get("name")
else:
name = None
if name:
names.append(name)
return names
def _history_names(payload: dict) -> list:
names = []
for message in payload.get("messages") or []:
if not isinstance(message, dict):
continue
for call in message.get("tool_calls") or []:
if not isinstance(call, dict):
continue
name = (call.get("function") or {}).get("name")
if name:
names.append(name)
return names
def tool_aliases_for(payload: dict) -> dict:
"""Map {alias: original} for reserved names in this Chat payload.
Deterministic: same payload always yields the same map, so the
send boundary and the response converter rebuild it independently
without threading state through the fallback path.
"""
declared = _declared_names(payload)
taken = set(declared)
seen = set()
aliases = {}
for name in list(declared) + _history_names(payload):
if name in MUSE_RESERVED_TOOL_NAMES and name not in seen:
seen.add(name)
aliases[_alias_for(name, taken)] = name
return aliases
def _restore(name, aliases: dict):
if not aliases or not isinstance(name, str):
return name
return aliases.get(name, name)
def _alias(name, forward: dict):
if not forward or not isinstance(name, str):
return name
return forward.get(name, name)
def alias_chat_tools(payload: dict, aliases: dict) -> dict:
"""Rewrite reserved tool names to their aliases (Meta wire shape).
Covers tools[], tool_choice (function + allowed_tools), and history
tool_calls so the model sees one consistent world. Returns the SAME
object untouched when there is nothing to alias.
"""
if not aliases:
return payload
forward = {original: alias for alias, original in aliases.items()}
renamed = dict(payload)
tools = []
for tool in payload.get("tools") or []:
if (
isinstance(tool, dict)
and tool.get("type") == "function"
and isinstance(tool.get("function"), dict)
):
func = dict(tool["function"])
func["name"] = _alias(func.get("name"), forward)
tool = {**tool, "function": func}
tools.append(tool)
if tools:
renamed["tools"] = tools
choice = renamed.get("tool_choice")
if isinstance(choice, dict):
if choice.get("type") == "function" and isinstance(
choice.get("function"), dict
):
func = dict(choice["function"])
func["name"] = _alias(func.get("name"), forward)
renamed["tool_choice"] = {**choice, "function": func}
elif choice.get("type") == "allowed_tools":
entries = []
for entry in choice.get("tools") or []:
if (
isinstance(entry, dict)
and entry.get("type") == "function"
and isinstance(entry.get("function"), dict)
):
func = dict(entry["function"])
func["name"] = _alias(func.get("name"), forward)
entry = {**entry, "function": func}
entries.append(entry)
renamed["tool_choice"] = {**choice, "tools": entries}
messages = []
for message in payload.get("messages") or []:
if isinstance(message, dict) and message.get("tool_calls"):
calls = []
for call in message["tool_calls"]:
if isinstance(call, dict) and isinstance(
call.get("function"), dict
):
func = dict(call["function"])
func["name"] = _alias(func.get("name"), forward)
call = {**call, "function": func}
calls.append(call)
message = {**message, "tool_calls": calls}
messages.append(message)
if messages:
renamed["messages"] = messages
return renamed
def restore_completion_names(comp: dict, aliases: dict) -> dict:
"""Restore original tool names on a ChatCompletion object."""
if not aliases:
return comp
for choice in comp.get("choices") or []:
message = (choice or {}).get("message") or {}
for call in message.get("tool_calls") or []:
func = (call or {}).get("function")
if isinstance(func, dict):
func["name"] = _restore(func.get("name"), aliases)
return comp
def restore_chunk_names(chunk: dict, aliases: dict) -> dict:
"""Restore original tool names on a ChatCompletion chunk."""
if not aliases:
return chunk
for choice in chunk.get("choices") or []:
delta = (choice or {}).get("delta") or {}
for call in delta.get("tool_calls") or []:
func = (call or {}).get("function")
if isinstance(func, dict) and func.get("name"):
func["name"] = _restore(func["name"], aliases)
return chunk
_muse_session_id = generate_uid()
def muse_impersonation_headers() -> dict:
"""Reproduce the exact headers the real muse CLI sends.
Since the 2026-10-29 rollout api.meta.ai answers subscription-billed
keys from any other client with 403 client_attestation_denied; a live
probe stamping these headers (captured from Muse Code 1.4.14) got HTTP
200 back. The session id is stable for the process lifetime, mirroring
one long-running headless session.
"""
return {
"User-Agent": _muse_user_agent(),
"X-Client-Id": f"tbh:{MUSE_CLIENT_SURFACE}",
"X-Tbh-Session-Id": _muse_session_id,
"X-Meta-Ai-Gateway-Session-Id": _muse_session_id,
"X-Tbh-Thread-Id": _muse_session_id,
"X-Tbh-Root-Session-Id": _muse_session_id,
"X-Tbh-Agent-Role": "main",
"X-Tbh-Contributor-Mode": MUSE_CONTRIBUTOR_MODE,
}