fix(qwen): mirror Qwen Code 0.20 Python hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 15:38:46 -04:00
1 parent 3095661c9a
commit 8eecb67722
12 files changed
+2086 -915

No files matched your search

+181 -120
View File
@@ -1,139 +1,200 @@
"""Qwen Code home discovery, settings I/O, and runtime inspection."""
"""Strict Qwen Code managed runtime inspection."""
from __future__ import annotations
import json
import base64
import os
import re
import tempfile
from typing import Optional
from typing import Any, List, Optional
import urllib.parse
from ._dotenv import parse_dotenv
from ._transaction import (
FileChange,
read_optional,
regular_file_exists,
require_runtime,
source_change,
from ._managed_files import (
MAX_CONFIG_BYTES,
MAX_SECRET_BYTES,
physical_directory_exists,
physical_file_exists,
read_physical_file,
)
from .qwen_config import (
QwenDocument,
RenderedDocument,
create_owned_document,
parse_document,
)
from .qwen_contract import AGENT_KEY, JsonObject, RuntimeContract, same_agent_id
from ._strict_json import JsonObject, parse_json_object
from .guard_template import generate_guard_script
from .hook_template import generate_hook_script
from .qwen_command import same_qwen_agent_id, same_qwen_path
from .qwen_contract import AGENT_KEY, QwenRuntimeContract, elydora_dir
def _default_qwen_home() -> str:
home_dir = os.path.expanduser("~")
if not home_dir or home_dir == "~":
home_dir = tempfile.gettempdir()
return os.path.join(home_dir, ".qwen")
def _resolve_storage_path(value: str) -> str:
resolved = value
if value == "~":
resolved = os.path.expanduser("~")
elif value.startswith(("~/", "~\\")):
segments = [item for item in re.split(r"[/\\]+", value[2:]) if item]
resolved = os.path.join(os.path.expanduser("~"), *segments)
return resolved if os.path.isabs(resolved) else os.path.abspath(resolved)
def _qwen_home_from_env_file(file_path: str) -> Optional[str]:
raw = read_optional(file_path, "Qwen home environment")
if raw is None:
return None
value = parse_dotenv(raw).get("QWEN_HOME")
return value or None
def resolve_qwen_home() -> str:
initial_value = os.environ.get("QWEN_HOME")
initial_home = (
_resolve_storage_path(initial_value) if initial_value else _default_qwen_home()
)
if "QWEN_HOME" in os.environ:
return initial_home
candidates = (
os.path.join(initial_home, ".env"),
os.path.join(os.path.dirname(initial_home), ".env"),
)
for candidate in candidates:
discovered = _qwen_home_from_env_file(candidate)
if discovered:
return _resolve_storage_path(discovered)
return initial_home
def read_document() -> QwenDocument:
config_path = os.path.join(resolve_qwen_home(), "settings.json")
raw = read_optional(config_path, "Qwen Code settings")
if raw is None:
return create_owned_document(config_path)
return parse_document(exists=True, file_path=config_path, raw=raw)
def rendered_change(rendered: RenderedDocument) -> Optional[FileChange]:
if not rendered.changed:
return None
return source_change(
rendered.document.file_path,
"Qwen Code settings",
rendered.document.raw if rendered.document.exists else None,
rendered.next_source,
0o600,
)
def _read_runtime_config(file_path: str) -> Optional[JsonObject]:
raw = read_optional(file_path, "Elydora runtime config")
if raw is None:
return None
def validate_api_origin(value: str, label: str = "base_url") -> None:
try:
value = json.loads(raw)
except json.JSONDecodeError as error:
parsed = urllib.parse.urlsplit(value)
hostname = parsed.hostname
parsed.port
except ValueError as error:
raise ValueError(f"{label} must be an absolute HTTP or HTTPS URL") from error
invalid_character = "\\" in value or any(
character.isspace() or ord(character) < 32 for character in value
)
if (
parsed.scheme not in ("http", "https")
or not parsed.netloc
or hostname is None
or invalid_character
):
raise ValueError(f"{label} must be an absolute HTTP or HTTPS URL")
if (
parsed.username is not None
or parsed.password is not None
or parsed.query
or parsed.fragment
):
raise ValueError(
f"Failed to parse Elydora runtime config at {file_path}: {error}"
f"{label} must exclude credentials, query parameters, and fragments"
)
def validate_private_key(value: str, label: str = "private_key") -> None:
try:
padded = value + "=" * ((4 - len(value) % 4) % 4)
seed = base64.b64decode(
padded.replace("-", "+").replace("_", "/"), validate=True
)
canonical = base64.urlsafe_b64encode(seed).rstrip(b"=").decode("ascii")
except (ValueError, UnicodeEncodeError) as error:
raise ValueError(
f"{label} must be a canonical 32-byte base64url value"
) from error
if not isinstance(value, dict):
if len(seed) != 32 or canonical != value:
raise ValueError(f"{label} must be a canonical 32-byte base64url value")
def _require_non_empty_string(
value: Any, field: str, config_path: str
) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError(
f"Elydora runtime config at {file_path} must contain a JSON object"
f"Elydora runtime config {field} is invalid: {config_path}"
)
return value
def runtime_files_exist(contracts: list[RuntimeContract]) -> bool:
for contract in contracts:
agent_directory = os.path.dirname(contract.guard_path)
runtime_config = _read_runtime_config(
os.path.join(agent_directory, "config.json")
def _validate_runtime_config(
config: JsonObject, expected_agent_id: str, config_path: str
) -> None:
supported = {"org_id", "agent_id", "kid", "base_url", "token", "agent_name"}
extra = next((key for key in config if key not in supported), None)
if extra is not None:
raise ValueError(
f'Elydora runtime config has unsupported field "{extra}": {config_path}'
)
config_agent_id = runtime_config.get("agent_id") if runtime_config else None
if (
runtime_config is None
or runtime_config.get("agent_name") != AGENT_KEY
or not isinstance(config_agent_id, str)
or not same_agent_id(config_agent_id, contract.agent_id)
):
continue
if regular_file_exists(
contract.guard_path,
"Elydora guard runtime",
) and regular_file_exists(
contract.audit_path,
"Elydora audit runtime",
):
return True
return False
_require_non_empty_string(config.get("org_id"), "org_id", config_path)
_require_non_empty_string(config.get("kid"), "kid", config_path)
agent_id = _require_non_empty_string(
config.get("agent_id"), "agent_id", config_path
)
if (
not same_qwen_agent_id(agent_id, expected_agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
"Elydora runtime identity does not match Qwen Code hooks: "
f"{config_path}"
)
if "token" in config:
_require_non_empty_string(config.get("token"), "token", config_path)
base_url = _require_non_empty_string(
config.get("base_url"), "base_url", config_path
)
validate_api_origin(base_url, "Elydora runtime config base_url")
__all__ = [
"read_document",
"rendered_change",
"require_runtime",
"resolve_qwen_home",
"runtime_files_exist",
]
def _read_runtime_config(file_path: str) -> Optional[JsonObject]:
snapshot = read_physical_file(
file_path, "Elydora runtime config", MAX_CONFIG_BYTES
)
if snapshot is None:
return None
return parse_json_object(
snapshot.contents, f"Elydora runtime config at {file_path}"
)
def validate_runtime_tree(agent_directory: str, agent_id: str) -> None:
root = elydora_dir()
if not physical_directory_exists(root, "Elydora runtime directory"):
return
if not physical_directory_exists(
agent_directory, "Elydora agent runtime directory"
):
return
config_path = os.path.join(agent_directory, "config.json")
config = _read_runtime_config(config_path)
artifacts = (
("private.key", "Elydora private key"),
("guard.py", "Elydora guard runtime"),
("hook.py", "Elydora audit runtime"),
("chain-state.json", "Elydora chain state"),
("status-cache.json", "Elydora status cache"),
("error.log", "Elydora error log"),
)
artifact_exists = any(
physical_file_exists(os.path.join(agent_directory, name), label)
for name, label in artifacts
)
if config is None:
if artifact_exists:
raise ValueError(
"Elydora runtime identity cannot be verified without config.json: "
f"{agent_directory}"
)
return
configured_id = config.get("agent_id")
if (
not isinstance(configured_id, str)
or not same_qwen_agent_id(configured_id, agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
"Elydora runtime config identity does not match Qwen Code agent "
f"{agent_id}: {config_path}"
)
def _runtime_contract_exists(contract: QwenRuntimeContract) -> bool:
root = elydora_dir()
agent_directory = os.path.dirname(contract.guard_path)
if (
not same_qwen_path(os.path.dirname(agent_directory), root)
or not same_qwen_path(
contract.audit_path, os.path.join(agent_directory, "hook.py")
)
):
return False
if not physical_directory_exists(root, "Elydora runtime directory"):
return False
if not physical_directory_exists(
agent_directory, "Elydora agent runtime directory"
):
return False
config_path = os.path.join(agent_directory, "config.json")
key_path = os.path.join(agent_directory, "private.key")
config = _read_runtime_config(config_path)
key = read_physical_file(key_path, "Elydora private key", MAX_SECRET_BYTES)
guard = read_physical_file(contract.guard_path, "Elydora guard runtime")
audit = read_physical_file(contract.audit_path, "Elydora audit runtime")
if config is None or key is None or guard is None or audit is None:
return False
_validate_runtime_config(config, contract.agent_id, config_path)
validate_private_key(key.contents, "Elydora private key")
expected_guard = generate_guard_script(AGENT_KEY, contract.agent_id)
expected_audit = generate_hook_script(
org_id=str(config["org_id"]),
agent_id=contract.agent_id,
kid=str(config["kid"]),
base_url=str(config["base_url"]),
native_payload=True,
agent_name=AGENT_KEY,
)
return guard.contents == expected_guard and audit.contents == expected_audit
def qwen_runtime_files_exist(
contracts: List[QwenRuntimeContract],
) -> bool:
return any(_runtime_contract_exists(contract) for contract in contracts)