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

+59 -134
View File
@@ -1,161 +1,86 @@
"""Qwen Code native global user-hook integration."""
"""Qwen Code 0.20 native global user-hook integration."""
from __future__ import annotations
import json
import os
from typing import List, Optional
from typing import Dict
from ._transaction import FileChange, file_change, write_changes
from .base import AgentPlugin, InstallConfig, PluginStatus
from .hook_template import generate_hook_script
from .qwen_config import render_document
from .qwen_config import render_qwen_document
from .qwen_contract import (
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
build_group,
elydora_dir,
runtime_contracts,
validate_javascript_regexes,
AUDIT_HOOK_NAME,
GUARD_HOOK_NAME,
JsonObject,
build_qwen_group,
qwen_runtime_contracts,
)
from .qwen_io import (
read_document,
rendered_change,
require_runtime,
runtime_files_exist,
from .qwen_installation import (
QwenRuntimePaths,
commit_qwen_installation,
commit_qwen_uninstall,
preflight_qwen_installation,
prepare_qwen_installation,
prepare_qwen_uninstall,
)
from .qwen_io import qwen_runtime_files_exist
from .qwen_sources import read_qwen_sources
def _agent_directory(agent_id: str) -> str:
if (
not agent_id
or agent_id in {".", ".."}
or os.path.basename(agent_id) != agent_id
or os.path.isabs(agent_id)
):
raise ValueError("agent_id must be a single non-empty path segment")
return os.path.join(elydora_dir(), agent_id)
def _same_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def _append_change(changes: List[FileChange], change: Optional[FileChange]) -> None:
if change is not None:
changes.append(change)
def _installed_groups(paths: QwenRuntimePaths) -> Dict[str, JsonObject]:
return {
"PreToolUse": build_qwen_group(paths.guard_path, GUARD_HOOK_NAME),
"PostToolUse": build_qwen_group(paths.audit_path, AUDIT_HOOK_NAME),
"PostToolUseFailure": build_qwen_group(
paths.audit_path, AUDIT_HOOK_NAME
),
}
class QwenPlugin(AgentPlugin):
"""Install Elydora into Qwen Code's global user settings."""
"""Install Elydora into Qwen Code's native user settings."""
manages_guard_runtime = True
def preflight_install(self, config: InstallConfig) -> None:
sources = read_qwen_sources()
preflight_qwen_installation(config, sources)
def install(self, config: InstallConfig) -> None:
agent_id = config.get("agent_id", "")
agent_directory = _agent_directory(agent_id)
document = read_document()
validate_javascript_regexes([document.hooks])
guard_path = config.get("guard_script_path", "")
expected_guard_path = os.path.join(agent_directory, GUARD_SCRIPT)
if not _same_path(guard_path, expected_guard_path):
raise ValueError(
"Elydora guard runtime must use the managed agent directory: "
f"{expected_guard_path}"
)
require_runtime(guard_path, "Elydora guard runtime")
audit_path = os.path.join(agent_directory, AUDIT_SCRIPT)
rendered = render_document(
document,
sources = read_qwen_sources()
paths = preflight_qwen_installation(config, sources)
rendered = render_qwen_document(
sources.user,
None,
{
"PreToolUse": build_group(guard_path),
"PostToolUse": build_group(audit_path),
},
_installed_groups(paths),
)
runtime_config = {
"org_id": config.get("org_id", ""),
"agent_id": agent_id,
"kid": config.get("kid", ""),
"base_url": config.get("base_url", "https://api.elydora.com"),
"token": config.get("token", ""),
"agent_name": AGENT_KEY,
}
audit_script = generate_hook_script(
org_id=config.get("org_id", ""),
agent_id=agent_id,
kid=config.get("kid", ""),
base_url=config.get("base_url", "https://api.elydora.com"),
)
changes: List[FileChange] = []
_append_change(
changes,
file_change(
os.path.join(agent_directory, "config.json"),
"Elydora runtime config",
json.dumps(runtime_config, indent=2) + "\n",
0o600,
),
)
_append_change(
changes,
file_change(
os.path.join(agent_directory, "private.key"),
"Elydora private key",
config.get("private_key", ""),
0o600,
),
)
_append_change(
changes,
file_change(
audit_path,
"Elydora audit runtime",
audit_script,
0o700,
),
)
_append_change(changes, rendered_change(rendered))
write_changes(changes, "Write Qwen Code installation")
print(f"Qwen Code: user hooks installed at {document.file_path}")
print("Qwen Code: run /hooks to review the Elydora hook changes.")
changes = prepare_qwen_installation(config, paths, rendered)
commit_qwen_installation(changes, sources)
print(f"Qwen Code hooks installed at {sources.user.file_path}")
print("Qwen Code verification: run /hooks and restart active sessions.")
def uninstall(self, agent_id: str = "") -> None:
document = read_document()
if not document.exists:
return
rendered = render_document(document, agent_id or None, {})
change = rendered_change(rendered)
write_changes(
[change] if change is not None else [],
"Write Qwen Code settings",
sources = read_qwen_sources()
rendered = render_qwen_document(
sources.user, agent_id or None, {}
)
commit_qwen_uninstall(prepare_qwen_uninstall(rendered), sources)
def status(self) -> PluginStatus:
document = read_document()
contracts = runtime_contracts(document.hooks)
if document.hooks_disabled:
return PluginStatus(
installed=False,
agent=AGENT_KEY,
details=f"Configured hooks are disabled: {document.file_path}",
sources = read_qwen_sources()
contracts = qwen_runtime_contracts(sources.user.hooks)
configured = not sources.disable_control.disabled and bool(contracts)
installed = configured and qwen_runtime_files_exist(contracts)
if installed:
details = f"Config: {sources.user.file_path}"
elif contracts and sources.disable_control.disabled:
details = f"Configured hooks are disabled: {sources.user.file_path}"
elif contracts:
details = (
f"Configured at {sources.user.file_path}; "
"managed contract incomplete"
)
if not contracts:
return PluginStatus(
installed=False,
agent=AGENT_KEY,
details="Not installed",
)
installed = runtime_files_exist(contracts)
details = (
f"Config: {document.file_path}"
if installed
else f"Configured at {document.file_path}; runtime scripts missing"
)
else:
details = "Not installed"
return PluginStatus(
installed=installed,
agent=AGENT_KEY,
+134
View File
@@ -0,0 +1,134 @@
"""Qwen Code command construction and exact runtime ownership."""
from __future__ import annotations
from dataclasses import dataclass
import os
import sys
from typing import Optional, Tuple
@dataclass(frozen=True)
class QwenRuntimeReference:
agent_id: str
script_path: str
def same_qwen_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def same_qwen_agent_id(left: str, right: str) -> bool:
return os.path.normcase(left) == os.path.normcase(right)
def _quote_posix(value: str) -> str:
return "'" + value.replace("'", "'\"'\"'") + "'"
def _quote_powershell(value: str) -> str:
return "'" + value.replace("'", "''") + "'"
def build_qwen_command(script_path: str) -> str:
if not os.path.isabs(sys.executable) or not os.path.isabs(script_path):
raise ValueError(
"Qwen Code hook commands require absolute executable and script paths"
)
invocation = (
f"{_quote_powershell(sys.executable)} {_quote_powershell(script_path)}"
if os.name == "nt"
else f"{_quote_posix(sys.executable)} {_quote_posix(script_path)}"
)
return f"& {invocation}; exit $LASTEXITCODE" if os.name == "nt" else invocation
def _read_posix_argument(command: str, start: int) -> Optional[Tuple[str, int]]:
if start >= len(command) or command[start] != "'":
return None
apostrophe = "'\"'\"'"
value = ""
index = start + 1
while index < len(command):
if command.startswith(apostrophe, index):
value += "'"
index += len(apostrophe)
continue
if command[index] == "'":
return value, index + 1
value += command[index]
index += 1
return None
def _parse_posix_command(command: str) -> Optional[Tuple[str, str]]:
executable = _read_posix_argument(command, 0)
if executable is None or executable[1] >= len(command):
return None
if command[executable[1]] != " ":
return None
script = _read_posix_argument(command, executable[1] + 1)
if script is None or script[1] != len(command):
return None
return executable[0], script[0]
def _read_powershell_argument(
command: str, start: int
) -> Optional[Tuple[str, int]]:
if start >= len(command) or command[start] != "'":
return None
value = ""
index = start + 1
while index < len(command):
if command[index] != "'":
value += command[index]
index += 1
continue
if index + 1 < len(command) and command[index + 1] == "'":
value += "'"
index += 2
continue
return value, index + 1
return None
def _parse_powershell_command(command: str) -> Optional[Tuple[str, str]]:
if not command.startswith("& "):
return None
executable = _read_powershell_argument(command, 2)
if executable is None or executable[1] >= len(command):
return None
if command[executable[1]] != " ":
return None
script = _read_powershell_argument(command, executable[1] + 1)
if script is None or command[script[1] :] != "; exit $LASTEXITCODE":
return None
return executable[0], script[0]
def qwen_runtime_reference(
command: str, script_name: str
) -> Optional[QwenRuntimeReference]:
parsed = (
_parse_powershell_command(command)
if os.name == "nt"
else _parse_posix_command(command)
)
if (
parsed is None
or not same_qwen_path(parsed[0], sys.executable)
or not os.path.isabs(parsed[1])
or os.path.basename(parsed[1]) != script_name
):
return None
agent_directory = os.path.dirname(parsed[1])
runtime_root = os.path.join(os.path.expanduser("~"), ".elydora")
if not same_qwen_path(os.path.dirname(agent_directory), runtime_root):
return None
agent_id = os.path.basename(agent_directory)
if agent_id in {"", ".", ".."}:
return None
return QwenRuntimeReference(agent_id, parsed[1])
+129 -77
View File
@@ -1,4 +1,4 @@
"""Qwen Code settings parsing and source-preserving rendering."""
"""Qwen Code JSONC parsing and source-preserving hook edits."""
from __future__ import annotations
@@ -6,12 +6,13 @@ from dataclasses import dataclass
from typing import Dict, Optional
from ._jsonc import JsoncEditor
from ._managed_files import FileSnapshot
from .qwen_contract import (
TOOL_EVENTS,
MANAGED_EVENTS,
JsonObject,
QwenHookSettings,
managed_removals,
read_hook_settings,
QwenHooks,
managed_qwen_removals,
read_qwen_hooks,
)
@@ -20,83 +21,121 @@ OWNED_FILE_MARKER = "// Managed by Elydora"
@dataclass(frozen=True)
class QwenDocument:
kind: str
file_path: str
exists: bool
raw: str
snapshot: Optional[FileSnapshot]
root: JsonObject
hooks: QwenHookSettings
hooks: QwenHooks
has_hooks_container: bool
hooks_disabled: bool
disable_all_hooks: Optional[bool]
folder_trust_enabled: Optional[bool]
owned_file: bool
@dataclass(frozen=True)
class RenderedDocument:
class RenderedQwenDocument:
document: QwenDocument
changed: bool
next_source: Optional[str]
def _label(file_path: str) -> str:
return f"Qwen Code settings at {file_path}"
def qwen_source_label(kind: str) -> str:
labels = {
"system-defaults": "Qwen Code system defaults",
"user": "Qwen Code user settings",
"workspace": "Qwen Code workspace settings",
"system": "Qwen Code system override settings",
}
try:
return labels[kind]
except KeyError as error:
raise ValueError(f"Unsupported Qwen Code document kind: {kind}") from error
def parse_document(
def qwen_document_label(document: QwenDocument) -> str:
return qwen_source_label(document.kind)
def parse_qwen_jsonc_object(raw: str, label: str) -> JsonObject:
editor = JsoncEditor(raw, label, allow_trailing_commas=False)
if not isinstance(editor.value, dict):
raise ValueError(f"{label} must contain a JSON object")
return editor.value
def _folder_trust_enabled(
root: JsonObject, label: str
) -> Optional[bool]:
if "security" not in root:
return None
security = root["security"]
if not isinstance(security, dict):
raise ValueError(f'{label} field "security" must be an object')
if "folderTrust" not in security:
return None
folder_trust = security["folderTrust"]
if not isinstance(folder_trust, dict):
raise ValueError(
f'{label} field "security.folderTrust" must be an object'
)
enabled = folder_trust.get("enabled")
if enabled is not None and not isinstance(enabled, bool):
raise ValueError(
f'{label} field "security.folderTrust.enabled" must be a boolean'
)
return enabled
def parse_qwen_document(
*,
kind: str,
exists: bool,
file_path: str,
raw: str,
snapshot: Optional[FileSnapshot] = None,
) -> QwenDocument:
label = _label(file_path)
editor = JsoncEditor(
raw,
label,
allow_trailing_commas=False,
)
if not isinstance(editor.value, dict):
raise ValueError(f"{label} must contain a JSON object")
root = editor.value
label = f"{qwen_source_label(kind)} at {file_path}"
root = parse_qwen_jsonc_object(raw, label)
disabled = root.get("disableAllHooks")
if "disableAllHooks" in root and not isinstance(disabled, bool):
raise ValueError(f'{label} field "disableAllHooks" must be a boolean')
has_container = "hooks" in root
hooks = (
read_hook_settings(root["hooks"], f'{label} field "hooks"')
if has_container
else {}
)
has_hooks = "hooks" in root
return QwenDocument(
file_path,
exists,
raw,
root,
hooks,
has_container,
disabled is True,
raw.startswith(OWNED_FILE_MARKER),
kind=kind,
file_path=file_path,
exists=exists,
raw=raw,
snapshot=snapshot,
root=root,
hooks=read_qwen_hooks(root["hooks"]) if has_hooks else {},
has_hooks_container=has_hooks,
disable_all_hooks=disabled if isinstance(disabled, bool) else None,
folder_trust_enabled=_folder_trust_enabled(root, label),
owned_file=kind == "user" and raw.startswith(OWNED_FILE_MARKER),
)
def create_owned_document(file_path: str) -> QwenDocument:
return parse_document(
def create_qwen_document(kind: str, file_path: str) -> QwenDocument:
raw = f"{OWNED_FILE_MARKER}\n{{}}\n" if kind == "user" else "{}\n"
return parse_qwen_document(
kind=kind,
exists=False,
file_path=file_path,
raw=f"{OWNED_FILE_MARKER}\n{{}}\n",
raw=raw,
)
def _settings_from_editor(
editor: JsoncEditor,
document: QwenDocument,
) -> QwenHookSettings:
root = editor.value
if not isinstance(root, dict):
raise ValueError(f"{_label(document.file_path)} must contain a JSON object")
if "hooks" not in root:
return {}
return read_hook_settings(
root["hooks"],
f'{_label(document.file_path)} field "hooks"',
def _current_document(
document: QwenDocument, editor: JsoncEditor
) -> QwenDocument:
return parse_qwen_document(
kind=document.kind,
exists=document.exists,
file_path=document.file_path,
raw=editor.raw,
snapshot=document.snapshot,
)
@@ -105,8 +144,8 @@ def _remove_managed(
document: QwenDocument,
agent_id: Optional[str],
) -> None:
removals = managed_removals(document.hooks, agent_id)
for event in TOOL_EVENTS:
removals = managed_qwen_removals(document.hooks, agent_id)
for event in MANAGED_EVENTS:
event_removals = sorted(
(item for item in removals if item.event == event),
key=lambda item: item.group_index,
@@ -120,14 +159,12 @@ def _remove_managed(
for handler_index in sorted(removal.handler_indexes, reverse=True):
editor.delete((*group_path, "hooks", handler_index))
if event_removals:
current = _settings_from_editor(editor, document)
if event in current and not current[event]:
current = _current_document(document, editor)
if event in current.hooks and not current.hooks[event]:
editor.delete(("hooks", event))
root = editor.value
if isinstance(root, dict) and "hooks" in root:
current = _settings_from_editor(editor, document)
if not current:
editor.delete(("hooks",))
current = _current_document(document, editor)
if current.has_hooks_container and not current.hooks:
editor.delete(("hooks",))
def _append_group(
@@ -136,42 +173,57 @@ def _append_group(
event: str,
group: JsonObject,
) -> None:
root = editor.value
if not isinstance(root, dict):
raise ValueError(f"{_label(document.file_path)} must contain a JSON object")
if "hooks" not in root:
current = _current_document(document, editor)
if not current.has_hooks_container:
editor.add_property((), "hooks", {event: [group]})
return
current = _settings_from_editor(editor, document)
if event in current:
elif event in current.hooks:
editor.append(("hooks", event), group)
else:
editor.add_property(("hooks",), event, [group])
def render_document(
def _already_installed(
document: QwenDocument, additions: Dict[str, JsonObject]
) -> bool:
if set(additions) != set(MANAGED_EVENTS):
return False
removals = managed_qwen_removals(document.hooks)
for event in MANAGED_EVENTS:
expected = additions[event]
event_removals = [item for item in removals if item.event == event]
exact_groups = [
group for group in document.hooks.get(event, []) if group == expected
]
if (
len(event_removals) != 1
or not event_removals[0].remove_group
or len(exact_groups) != 1
):
return False
return True
def render_qwen_document(
document: QwenDocument,
agent_id: Optional[str],
additions: Dict[str, JsonObject],
) -> RenderedDocument:
) -> RenderedQwenDocument:
if agent_id is None and _already_installed(document, additions):
return RenderedQwenDocument(document, False, document.raw)
editor = JsoncEditor(
document.raw,
_label(document.file_path),
f"{qwen_document_label(document)} at {document.file_path}",
allow_trailing_commas=False,
)
_remove_managed(editor, document, agent_id)
for event in TOOL_EVENTS:
for event in MANAGED_EVENTS:
group = additions.get(event)
if group is not None:
_append_group(editor, document, event, group)
next_document = parse_document(
exists=document.exists,
file_path=document.file_path,
raw=editor.raw,
)
if not additions and document.owned_file and not next_document.root:
return RenderedDocument(document, True, None)
return RenderedDocument(
current = _current_document(document, editor)
if not additions and document.owned_file and not current.root:
return RenderedQwenDocument(document, True, None)
return RenderedQwenDocument(
document,
editor.raw != document.raw,
editor.raw,
+220 -221
View File
@@ -1,4 +1,4 @@
"""Qwen Code hook schema, commands, and exact ownership rules."""
"""Qwen Code 0.20 hook schema and exact ownership rules."""
from __future__ import annotations
@@ -8,17 +8,26 @@ import math
import os
import shutil
import subprocess # nosec B404
import sys
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
from typing import Any, Dict, List, Optional, Sequence, Tuple
from .qwen_command import (
QwenRuntimeReference,
build_qwen_command,
qwen_runtime_reference,
same_qwen_agent_id,
same_qwen_path,
)
AGENT_KEY = "qwen"
GUARD_SCRIPT = "guard.py"
AUDIT_SCRIPT = "hook.py"
GUARD_HOOK_NAME = "elydora-guard"
AUDIT_HOOK_NAME = "elydora-audit"
HOOK_TIMEOUT_MILLISECONDS = 10_000
TOOL_EVENTS = ("PreToolUse", "PostToolUse")
MANAGED_EVENTS = ("PreToolUse", "PostToolUse", "PostToolUseFailure")
_EVENT_NAMES = {
KNOWN_EVENTS = {
"PreToolUse",
"PostToolUse",
"PostToolUseFailure",
@@ -41,9 +50,25 @@ _EVENT_NAMES = {
"TodoCompleted",
"InstructionsLoaded",
}
_CONFIG_FIELDS = {"enabled", "disabled", "notifications"}
_HANDLER_KEYS = {"command", "shell", "timeout", "type"}
_GROUP_KEYS = {"hooks", "matcher"}
REGEX_MATCHER_EVENTS = {
"PreToolUse",
"PostToolUse",
"PostToolUseFailure",
"PermissionRequest",
"PermissionDenied",
"SubagentStart",
"SubagentStop",
"PreCompact",
"PostCompact",
"SessionStart",
"SessionEnd",
"StopFailure",
"Notification",
"InstructionsLoaded",
"UserPromptExpansion",
}
_REGEX_TIMEOUT_SECONDS = 10
_REGEX_VALIDATOR = """import fs from 'node:fs';
const entries = JSON.parse(fs.readFileSync(0, 'utf8'));
@@ -59,11 +84,11 @@ for (const entry of entries) {
"""
JsonObject = Dict[str, Any]
QwenHookSettings = Dict[str, Any]
QwenHooks = Dict[str, Any]
@dataclass(frozen=True)
class RuntimeContract:
class QwenRuntimeContract:
agent_id: str
guard_path: str
audit_path: str
@@ -81,67 +106,37 @@ def elydora_dir() -> str:
return os.path.join(os.path.expanduser("~"), ".elydora")
def _quote_posix(value: str) -> str:
return "'" + value.replace("'", "'\"'\"'") + "'"
def _optional_string(value: JsonObject, field: str, label: str) -> None:
if field in value and not isinstance(value[field], str):
raise ValueError(f'{label} field "{field}" must be a string')
def _quote_powershell(value: str) -> str:
return "'" + value.replace("'", "''") + "'"
def _optional_boolean(value: JsonObject, field: str, label: str) -> None:
if field in value and not isinstance(value[field], bool):
raise ValueError(f'{label} field "{field}" must be a boolean')
def build_command(script_path: str) -> str:
if os.name == "nt":
invocation = (
f"{_quote_powershell(sys.executable)} {_quote_powershell(script_path)}"
)
return f"& {invocation}; exit $LASTEXITCODE"
return f"{_quote_posix(sys.executable)} {_quote_posix(script_path)}"
def build_group(script_path: str) -> JsonObject:
return {
"matcher": "*",
"hooks": [
{
"type": "command",
"command": build_command(script_path),
"shell": "powershell" if os.name == "nt" else "bash",
"timeout": HOOK_TIMEOUT_MILLISECONDS,
}
],
}
def _optional_string(value: JsonObject, key: str, label: str) -> None:
if key in value and not isinstance(value[key], str):
raise ValueError(f'{label} field "{key}" must be a string')
def _optional_boolean(value: JsonObject, key: str, label: str) -> None:
if key in value and not isinstance(value[key], bool):
raise ValueError(f'{label} field "{key}" must be a boolean')
def _optional_string_map(value: JsonObject, key: str, label: str) -> None:
if key not in value:
def _optional_string_map(value: JsonObject, field: str, label: str) -> None:
if field not in value:
return
item = value[key]
item = value[field]
if not isinstance(item, dict) or any(
not isinstance(entry, str) for entry in item.values()
):
raise ValueError(f'{label} field "{key}" must contain string values')
raise ValueError(f'{label} field "{field}" must map names to strings')
def _validate_timeout(value: JsonObject, label: str) -> None:
if "timeout" not in value:
return
timeout = value["timeout"]
if (
isinstance(timeout, bool)
or not isinstance(timeout, (int, float))
or not math.isfinite(timeout)
or timeout < 0
):
try:
finite = math.isfinite(timeout)
except (TypeError, OverflowError):
finite = False
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not finite:
raise ValueError(f"{label} timeout must be a non-negative finite number")
if timeout < 0:
raise ValueError(f"{label} timeout must be a non-negative finite number")
@@ -151,20 +146,20 @@ def _validate_handler(value: Any, label: str) -> JsonObject:
handler = dict(value)
kind = handler.get("type")
if kind not in {"command", "http", "prompt"}:
raise ValueError(f'{label} type must be "command", "http", or "prompt"')
raise ValueError(f'{label} has unsupported type "{kind}"')
_validate_timeout(handler, label)
for key in ("name", "description", "statusMessage", "source"):
_optional_string(handler, key, label)
for field in ("name", "description", "statusMessage", "source"):
_optional_string(handler, field, label)
if kind == "command":
if not isinstance(handler.get("command"), str) or not handler["command"]:
raise ValueError(f"{label} command must be a non-empty string")
raise ValueError(f"{label} requires a non-empty command")
_optional_string_map(handler, "env", label)
_optional_boolean(handler, "async", label)
if "shell" in handler and handler["shell"] not in {"bash", "powershell"}:
raise ValueError(f'{label} shell must be "bash" or "powershell"')
elif kind == "http":
if not isinstance(handler.get("url"), str) or not handler["url"]:
raise ValueError(f"{label} url must be a non-empty string")
raise ValueError(f"{label} requires a non-empty url")
_optional_string_map(handler, "headers", label)
_optional_boolean(handler, "once", label)
_optional_string(handler, "if", label)
@@ -176,12 +171,13 @@ def _validate_handler(value: Any, label: str) -> JsonObject:
raise ValueError(f"{label} allowedEnvVars must be an array of strings")
else:
if not isinstance(handler.get("prompt"), str) or not handler["prompt"]:
raise ValueError(f"{label} prompt must be a non-empty string")
raise ValueError(f"{label} requires a non-empty prompt")
_optional_string(handler, "model", label)
return handler
def _validate_group(value: Any, label: str) -> JsonObject:
def _validate_group(value: Any, event: str, index: int) -> JsonObject:
label = f"Qwen Code settings group hooks.{event}[{index}]"
if not isinstance(value, dict):
raise ValueError(f"{label} must be an object")
group = dict(value)
@@ -193,49 +189,47 @@ def _validate_group(value: Any, label: str) -> JsonObject:
if not isinstance(handlers, list):
raise ValueError(f"{label} must contain a hooks array")
group["hooks"] = [
_validate_handler(handler, f"{label}.hooks[{index}]")
for index, handler in enumerate(handlers)
_validate_handler(handler, f"{label}.hooks[{handler_index}]")
for handler_index, handler in enumerate(handlers)
]
return group
def read_hook_settings(value: Any, label: str) -> QwenHookSettings:
def read_qwen_hooks(value: Any) -> QwenHooks:
if not isinstance(value, dict):
raise ValueError(f"{label} must contain a JSON object")
settings = dict(value)
raise ValueError('Qwen Code settings field "hooks" must be an object')
hooks: QwenHooks = {}
for event, groups in value.items():
if event in _CONFIG_FIELDS:
if event not in KNOWN_EVENTS:
hooks[event] = groups
continue
if event not in _EVENT_NAMES:
raise ValueError(f'{label} contains unsupported field "{event}"')
if not isinstance(groups, list):
raise ValueError(f'{label} field "{event}" must be an array')
settings[event] = [
_validate_group(group, f'{label} field "{event}"[{index}]')
raise ValueError(
f'Qwen Code settings field "hooks.{event}" must be an array'
)
hooks[event] = [
_validate_group(group, event, index)
for index, group in enumerate(groups)
]
return settings
return hooks
def _regex_entries(settings: QwenHookSettings) -> List[JsonObject]:
entries = []
for event, groups in settings.items():
if event in _CONFIG_FIELDS:
continue
for index, group in enumerate(groups):
matcher = group.get("matcher")
if isinstance(matcher, str) and matcher.strip() not in {"", "*"}:
entries.append(
{
"label": f'Qwen Code hooks field "{event}"[{index}] matcher',
def _matcher_entries(sources: Sequence[QwenHooks]) -> List[JsonObject]:
entries: List[JsonObject] = []
for hooks in sources:
for event in REGEX_MATCHER_EVENTS:
for index, group in enumerate(hooks.get(event, [])):
matcher = group.get("matcher")
if isinstance(matcher, str) and matcher.strip() not in {"", "*"}:
entries.append({
"label": f"Qwen Code settings group hooks.{event}[{index}]",
"pattern": matcher,
}
)
})
return entries
def validate_javascript_regexes(settings: Sequence[QwenHookSettings]) -> None:
entries = [entry for source in settings for entry in _regex_entries(source)]
def validate_javascript_matchers(sources: Sequence[QwenHooks]) -> None:
entries = _matcher_entries(sources)
if not entries:
return
node_path = shutil.which("node")
@@ -267,143 +261,148 @@ def validate_javascript_regexes(settings: Sequence[QwenHookSettings]) -> None:
or f"Node.js exited with code {result.returncode}"
)
raise ValueError(
f"Qwen Code matcher must be a valid JavaScript regular expression: {message}"
"Qwen Code matcher must be a valid JavaScript regular expression: "
+ message
)
def _read_quoted_argument(command: str, start: int) -> Optional[Tuple[str, int]]:
if start >= len(command) or command[start] != "'":
return None
value = ""
index = start + 1
while index < len(command):
if os.name == "nt" and command[index : index + 2] == "''":
value += "'"
index += 2
continue
if os.name != "nt" and command[index : index + 5] == "'\"'\"'":
value += "'"
index += 5
continue
if command[index] == "'":
return value, index + 1
value += command[index]
index += 1
return None
def _parse_generated_command(command: str) -> Optional[Tuple[str, str]]:
if os.name == "nt" and not command.startswith("& "):
return None
start = 2 if os.name == "nt" else 0
executable = _read_quoted_argument(command, start)
if executable is None or executable[1] >= len(command):
return None
if command[executable[1]] != " ":
return None
script = _read_quoted_argument(command, executable[1] + 1)
if script is None:
return None
suffix = "; exit $LASTEXITCODE" if os.name == "nt" else ""
if command[script[1] :] != suffix or not executable[0] or not script[0]:
return None
return executable[0], script[0]
def _same_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def same_agent_id(left: str, right: str) -> bool:
return os.path.normcase(left) == os.path.normcase(right)
def managed_agent_id(handler: JsonObject, script_name: str) -> Optional[str]:
if set(handler) != _HANDLER_KEYS:
return None
expected_shell = "powershell" if os.name == "nt" else "bash"
if (
handler.get("type") != "command"
or handler.get("timeout") != HOOK_TIMEOUT_MILLISECONDS
or handler.get("shell") != expected_shell
or not isinstance(handler.get("command"), str)
):
return None
parsed = _parse_generated_command(handler["command"])
if parsed is None or not _same_path(parsed[0], sys.executable):
return None
script_path = parsed[1]
if os.path.basename(script_path) != script_name:
return None
agent_directory = os.path.dirname(script_path)
if not _same_path(os.path.dirname(agent_directory), elydora_dir()):
return None
agent_id = os.path.basename(agent_directory)
return agent_id if agent_id not in {"", ".", ".."} else None
def _exact_owned_group(group: JsonObject, indexes: Tuple[int, ...]) -> bool:
return (
set(group) == _GROUP_KEYS
and group.get("matcher") == "*"
and bool(indexes)
and len(indexes) == len(group["hooks"])
)
def managed_removals(
settings: QwenHookSettings,
agent_id: Optional[str] = None,
) -> List[ManagedRemoval]:
removals = []
for event, script_name in (
("PreToolUse", GUARD_SCRIPT),
("PostToolUse", AUDIT_SCRIPT),
):
for group_index, group in enumerate(settings.get(event, [])):
indexes = tuple(
index
for index, handler in enumerate(group["hooks"])
if (
(managed_id := managed_agent_id(handler, script_name)) is not None
and (agent_id is None or same_agent_id(managed_id, agent_id))
)
)
if indexes:
removals.append(
ManagedRemoval(
event,
group_index,
indexes,
_exact_owned_group(group, indexes),
)
)
return removals
def _managed_ids(groups: List[JsonObject], script_name: str) -> Set[str]:
def build_qwen_group(script_path: str, name: str) -> JsonObject:
return {
agent_id
for group in groups
for handler in group["hooks"]
if (agent_id := managed_agent_id(handler, script_name)) is not None
"hooks": [{
"type": "command",
"name": name,
"command": build_qwen_command(script_path),
"shell": "powershell" if os.name == "nt" else "bash",
"timeout": HOOK_TIMEOUT_MILLISECONDS,
}]
}
def runtime_contracts(settings: QwenHookSettings) -> List[RuntimeContract]:
guards = _managed_ids(settings.get("PreToolUse", []), GUARD_SCRIPT)
audits = _managed_ids(settings.get("PostToolUse", []), AUDIT_SCRIPT)
contracts = []
for agent_id in sorted(guards, key=os.path.normcase):
if any(same_agent_id(agent_id, audit_id) for audit_id in audits):
root = os.path.join(elydora_dir(), agent_id)
contracts.append(
RuntimeContract(
agent_id,
os.path.join(root, GUARD_SCRIPT),
os.path.join(root, AUDIT_SCRIPT),
def _exact_current_group(group: JsonObject) -> bool:
return set(group) == {"hooks"}
def _exact_legacy_group(group: JsonObject) -> bool:
return set(group) == {"hooks", "matcher"} and group.get("matcher") == "*"
def _current_reference(
handler: JsonObject, script_name: str, hook_name: str
) -> Optional[QwenRuntimeReference]:
if (
set(handler) == {"command", "name", "shell", "timeout", "type"}
and handler.get("type") == "command"
and handler.get("name") == hook_name
and handler.get("shell") == ("powershell" if os.name == "nt" else "bash")
and handler.get("timeout") == HOOK_TIMEOUT_MILLISECONDS
and isinstance(handler.get("command"), str)
):
return qwen_runtime_reference(handler["command"], script_name)
return None
def _legacy_reference(
handler: JsonObject, script_name: str
) -> Optional[QwenRuntimeReference]:
if (
set(handler) == {"command", "shell", "timeout", "type"}
and handler.get("type") == "command"
and handler.get("shell") == ("powershell" if os.name == "nt" else "bash")
and handler.get("timeout") == HOOK_TIMEOUT_MILLISECONDS
and isinstance(handler.get("command"), str)
):
return qwen_runtime_reference(handler["command"], script_name)
return None
def _managed_reference(
handler: JsonObject,
script_name: str,
hook_name: str,
include_legacy: bool,
) -> Optional[QwenRuntimeReference]:
current = _current_reference(handler, script_name, hook_name)
if current is not None or not include_legacy:
return current
return _legacy_reference(handler, script_name)
_EVENT_CONTRACTS = (
("PreToolUse", GUARD_SCRIPT, GUARD_HOOK_NAME),
("PostToolUse", AUDIT_SCRIPT, AUDIT_HOOK_NAME),
("PostToolUseFailure", AUDIT_SCRIPT, AUDIT_HOOK_NAME),
)
def managed_qwen_removals(
hooks: QwenHooks, agent_id: Optional[str] = None
) -> List[ManagedRemoval]:
removals: List[ManagedRemoval] = []
for event, script_name, hook_name in _EVENT_CONTRACTS:
for group_index, group in enumerate(hooks.get(event, [])):
handlers = group["hooks"]
indexes = tuple(
index
for index, handler in enumerate(handlers)
if (
reference := _managed_reference(
handler, script_name, hook_name, True
)
)
is not None
and (
agent_id is None
or same_qwen_agent_id(reference.agent_id, agent_id)
)
)
if indexes:
removals.append(ManagedRemoval(
event,
group_index,
indexes,
(_exact_current_group(group) or _exact_legacy_group(group))
and len(indexes) == len(handlers),
))
return removals
def _references_for_event(
groups: List[JsonObject], script_name: str, hook_name: str
) -> Dict[str, List[QwenRuntimeReference]]:
references: Dict[str, List[QwenRuntimeReference]] = {}
for group in groups:
if not _exact_current_group(group):
continue
for handler in group["hooks"]:
reference = _current_reference(handler, script_name, hook_name)
if reference is None:
continue
key = os.path.normcase(reference.agent_id)
references.setdefault(key, []).append(reference)
return references
def qwen_runtime_contracts(hooks: QwenHooks) -> List[QwenRuntimeContract]:
guards = _references_for_event(
hooks.get("PreToolUse", []), GUARD_SCRIPT, GUARD_HOOK_NAME
)
posts = _references_for_event(
hooks.get("PostToolUse", []), AUDIT_SCRIPT, AUDIT_HOOK_NAME
)
failures = _references_for_event(
hooks.get("PostToolUseFailure", []), AUDIT_SCRIPT, AUDIT_HOOK_NAME
)
contracts: List[QwenRuntimeContract] = []
for key, guard in guards.items():
post = posts.get(key, [])
failure = failures.get(key, [])
if len(guard) != 1 or len(post) != 1 or len(failure) != 1:
continue
if not same_qwen_path(post[0].script_path, failure[0].script_path):
continue
contracts.append(QwenRuntimeContract(
guard[0].agent_id,
guard[0].script_path,
post[0].script_path,
))
return contracts
@@ -0,0 +1,198 @@
"""Transactional Qwen Code hook and runtime installation."""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from typing import List, Optional, Sequence
from elydora._runtime_paths import resolve_agent_directory
from ._managed_files import MAX_CONFIG_BYTES, MAX_SECRET_BYTES, MAX_SOURCE_BYTES
from ._transaction import FileChange, FilePrecondition, file_change, source_change, write_changes
from .base import InstallConfig
from .guard_template import generate_guard_script
from .hook_template import generate_hook_script
from .qwen_command import same_qwen_path
from .qwen_config import RenderedQwenDocument, qwen_document_label
from .qwen_contract import AGENT_KEY, AUDIT_SCRIPT, GUARD_SCRIPT, elydora_dir
from .qwen_io import validate_api_origin, validate_private_key, validate_runtime_tree
from .qwen_sources import QwenSources, require_qwen_hooks_enabled
@dataclass(frozen=True)
class QwenRuntimePaths:
agent_id: str
agent_directory: str
guard_path: str
audit_path: str
def _runtime_config(config: InstallConfig, agent_id: str) -> dict:
value = {
"org_id": config.get("org_id", ""),
"agent_id": agent_id,
"kid": config.get("kid", ""),
"base_url": config.get("base_url", "https://api.elydora.com"),
"agent_name": AGENT_KEY,
}
token = config.get("token")
if token:
value["token"] = token
return value
def _json_source(value: dict) -> str:
return json.dumps(value, indent=2) + "\n"
def _agent_paths(config: InstallConfig) -> QwenRuntimePaths:
agent_id = config.get("agent_id", "")
if not agent_id:
raise ValueError("agent_id is required")
agent_directory = resolve_agent_directory(elydora_dir(), agent_id)
guard_path = os.path.join(agent_directory, GUARD_SCRIPT)
audit_path = os.path.join(agent_directory, AUDIT_SCRIPT)
if not same_qwen_path(config.get("guard_script_path", ""), guard_path):
raise ValueError(
"Elydora guard runtime must use the managed agent directory: "
f"{guard_path}"
)
return QwenRuntimePaths(agent_id, agent_directory, guard_path, audit_path)
def _validate_install_config(config: InstallConfig) -> None:
for field in ("org_id", "agent_id", "kid", "private_key", "base_url"):
value = config.get(field)
if not isinstance(value, str) or not value:
raise ValueError(f"{field} is required")
if config.get("agent_name") != AGENT_KEY:
raise ValueError(
f"Qwen Code installation requires agent_name {AGENT_KEY}"
)
validate_private_key(config["private_key"])
validate_api_origin(config["base_url"])
if "token" in config:
token = config["token"]
if not isinstance(token, str) or not token:
raise ValueError("token must be a non-empty string when provided")
_agent_paths(config)
def preflight_qwen_installation(
config: InstallConfig, sources: QwenSources
) -> QwenRuntimePaths:
require_qwen_hooks_enabled(sources)
_validate_install_config(config)
paths = _agent_paths(config)
validate_runtime_tree(paths.agent_directory, paths.agent_id)
return paths
def _runtime_change(
file_path: str,
label: str,
next_source: str,
mode: int,
maximum_bytes: int = MAX_SOURCE_BYTES,
) -> Optional[FileChange]:
return file_change(file_path, label, next_source, mode, maximum_bytes)
def _rendered_change(
rendered: RenderedQwenDocument,
) -> Optional[FileChange]:
if not rendered.changed:
return None
return source_change(
rendered.document.file_path,
qwen_document_label(rendered.document),
rendered.document.raw if rendered.document.exists else None,
rendered.next_source,
0o600,
MAX_SOURCE_BYTES,
expected_snapshot=rendered.document.snapshot,
)
def _present(changes: Sequence[Optional[FileChange]]) -> List[FileChange]:
return [change for change in changes if change is not None]
def prepare_qwen_installation(
config: InstallConfig,
paths: QwenRuntimePaths,
rendered: RenderedQwenDocument,
) -> List[FileChange]:
guard_script = generate_guard_script(AGENT_KEY, paths.agent_id)
audit_script = generate_hook_script(
org_id=config.get("org_id", ""),
agent_id=paths.agent_id,
kid=config.get("kid", ""),
base_url=config.get("base_url", "https://api.elydora.com"),
native_payload=True,
agent_name=AGENT_KEY,
)
return _present([
_runtime_change(
paths.guard_path, "Elydora guard runtime", guard_script, 0o700
),
_runtime_change(
os.path.join(paths.agent_directory, "config.json"),
"Elydora runtime config",
_json_source(_runtime_config(config, paths.agent_id)),
0o600,
MAX_CONFIG_BYTES,
),
_runtime_change(
os.path.join(paths.agent_directory, "private.key"),
"Elydora private key",
config.get("private_key", ""),
0o600,
MAX_SECRET_BYTES,
),
_runtime_change(
paths.audit_path, "Elydora audit runtime", audit_script, 0o700
),
_rendered_change(rendered),
])
def _read_only_preconditions(
sources: QwenSources, changed_path: Optional[str]
) -> List[FilePrecondition]:
return [
condition
for condition in sources.preconditions
if changed_path is None
or not same_qwen_path(condition.file_path, changed_path)
]
def commit_qwen_installation(
changes: List[FileChange], sources: QwenSources
) -> None:
write_changes(
changes,
"Install Qwen Code hooks",
_read_only_preconditions(sources, sources.user.file_path),
)
def prepare_qwen_uninstall(
rendered: RenderedQwenDocument,
) -> Optional[FileChange]:
return _rendered_change(rendered)
def commit_qwen_uninstall(
change: Optional[FileChange], sources: QwenSources
) -> None:
if change is None:
return
write_changes(
[change],
"Uninstall Qwen Code hooks",
_read_only_preconditions(sources, sources.user.file_path),
)
+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)
+373
View File
@@ -0,0 +1,373 @@
"""Qwen Code 0.20 settings discovery, trust, and effective controls."""
from __future__ import annotations
from dataclasses import dataclass
import os
import re
import sys
import tempfile
from typing import Dict, List, Optional, Set, Tuple
from ._dotenv import parse_dotenv
from ._managed_files import MAX_SOURCE_BYTES, FileSnapshot, read_physical_file
from ._transaction import FilePrecondition
from .qwen_command import same_qwen_path
from .qwen_config import (
QwenDocument,
create_qwen_document,
parse_qwen_document,
parse_qwen_jsonc_object,
qwen_document_label,
qwen_source_label,
)
from .qwen_contract import validate_javascript_matchers
_HOME_ENV_KEYS = ("QWEN_HOME", "QWEN_RUNTIME_DIR")
@dataclass(frozen=True)
class QwenDisableControl:
disabled: bool
source: Optional[QwenDocument]
@dataclass(frozen=True)
class QwenSources:
qwen_home: str
system_defaults: QwenDocument
user: QwenDocument
workspace: QwenDocument
system: QwenDocument
workspace_active: bool
workspace_trusted: bool
disable_control: QwenDisableControl
preconditions: Tuple[FilePrecondition, ...]
@dataclass(frozen=True)
class _RoutingResult:
qwen_home: str
preconditions: Tuple[FilePrecondition, ...]
def _default_qwen_home() -> str:
home = os.path.expanduser("~")
if not home or home == "~":
home = tempfile.gettempdir()
return os.path.join(home, ".qwen")
def _resolve_config_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 _environment_value(key: str) -> Tuple[bool, Optional[str]]:
return key in os.environ, os.environ.get(key)
def _resolve_qwen_routing() -> _RoutingResult:
values: Dict[str, Optional[str]] = {}
owned: Set[str] = set()
for key in _HOME_ENV_KEYS:
present, value = _environment_value(key)
values[key] = value
if present:
owned.add(key)
if all(values.get(key) for key in _HOME_ENV_KEYS):
return _RoutingResult(
_resolve_config_path(values["QWEN_HOME"] or ""), ()
)
initial_qwen_home = values.get("QWEN_HOME")
initial_directory = (
_resolve_config_path(initial_qwen_home)
if initial_qwen_home
else _default_qwen_home()
)
candidates = [os.path.join(initial_directory, ".env")]
if not initial_qwen_home:
candidates.append(os.path.join(os.path.dirname(initial_directory), ".env"))
preconditions: List[FilePrecondition] = []
visited: Set[str] = set()
def read_candidate(file_path: str) -> None:
resolved = os.path.abspath(file_path)
key = os.path.normcase(resolved)
if key in visited:
return
visited.add(key)
snapshot = read_physical_file(
resolved, "Qwen Code home environment", MAX_SOURCE_BYTES
)
preconditions.append(FilePrecondition(
resolved,
"Qwen Code home environment",
snapshot,
MAX_SOURCE_BYTES,
))
if snapshot is None:
return
parsed = parse_dotenv(snapshot.contents)
for env_key in _HOME_ENV_KEYS:
value = parsed.get(env_key)
if value and env_key not in owned:
values[env_key] = value
owned.add(env_key)
for candidate in candidates:
read_candidate(candidate)
discovered_home = values.get("QWEN_HOME")
if discovered_home and discovered_home != initial_qwen_home:
discovered_directory = _resolve_config_path(discovered_home)
if not same_qwen_path(discovered_directory, initial_directory):
read_candidate(os.path.join(discovered_directory, ".env"))
resolved_home = values.get("QWEN_HOME")
return _RoutingResult(
_resolve_config_path(resolved_home) if resolved_home else _default_qwen_home(),
tuple(preconditions),
)
def resolve_qwen_home() -> str:
return _resolve_qwen_routing().qwen_home
def _system_settings_path() -> str:
configured = os.environ.get("QWEN_CODE_SYSTEM_SETTINGS_PATH")
if configured:
return os.path.abspath(configured)
if sys.platform == "darwin":
return "/Library/Application Support/QwenCode/settings.json"
if os.name == "nt":
return r"C:\ProgramData\qwen-code\settings.json"
return "/etc/qwen-code/settings.json"
def _system_defaults_path(system_path: str) -> str:
configured = os.environ.get("QWEN_CODE_SYSTEM_DEFAULTS_PATH")
return (
os.path.abspath(configured)
if configured
else os.path.join(os.path.dirname(system_path), "system-defaults.json")
)
def _read_document(kind: str, file_path: str) -> QwenDocument:
snapshot = read_physical_file(
file_path, qwen_source_label(kind), MAX_SOURCE_BYTES
)
if snapshot is None:
return create_qwen_document(kind, file_path)
return parse_qwen_document(
kind=kind,
exists=True,
file_path=file_path,
raw=snapshot.contents,
snapshot=snapshot,
)
def _canonical_path(file_path: str) -> str:
try:
return os.path.realpath(file_path)
except OSError:
return os.path.abspath(file_path)
def _comparison_path(file_path: str) -> str:
return os.path.normcase(os.path.abspath(file_path))
def _is_within(child: str, parent: str) -> bool:
try:
relative = os.path.relpath(_comparison_path(child), _comparison_path(parent))
except ValueError:
return False
return relative == "." or (
relative != ".."
and not relative.startswith(".." + os.sep)
and not os.path.isabs(relative)
)
def _workspace_trust(
system: QwenDocument,
user: QwenDocument,
qwen_home: str,
workspace_path: str,
) -> Tuple[bool, Optional[FilePrecondition]]:
enabled = (
user.folder_trust_enabled
if user.folder_trust_enabled is not None
else system.folder_trust_enabled
)
if enabled is not True:
return True, None
configured = os.environ.get("QWEN_CODE_TRUSTED_FOLDERS_PATH")
file_path = (
os.path.abspath(configured)
if configured
else os.path.join(qwen_home, "trustedFolders.json")
)
snapshot = read_physical_file(
file_path, "Qwen Code trusted folders", MAX_SOURCE_BYTES
)
precondition = FilePrecondition(
file_path,
"Qwen Code trusted folders",
snapshot,
MAX_SOURCE_BYTES,
)
if snapshot is None:
return True, precondition
rules = parse_qwen_jsonc_object(
snapshot.contents, f"Qwen Code trusted folders at {file_path}"
)
allowed_levels = {"TRUST_FOLDER", "TRUST_PARENT", "DO_NOT_TRUST"}
for rule_path, level in rules.items():
if level not in allowed_levels:
raise ValueError(
"Qwen Code trusted folders has invalid trust level for "
f'"{rule_path}"'
)
workspace = _canonical_path(workspace_path)
for rule_path, level in rules.items():
canonical_rule = _canonical_path(rule_path)
trust_root = (
os.path.dirname(canonical_rule)
if level == "TRUST_PARENT"
else canonical_rule
)
if level in {"TRUST_FOLDER", "TRUST_PARENT"} and _is_within(
workspace, trust_root
):
return True, precondition
for rule_path, level in rules.items():
if level == "DO_NOT_TRUST" and _comparison_path(
workspace
) == _comparison_path(_canonical_path(rule_path)):
return False, precondition
return True, precondition
def _effective_disable(
system_defaults: QwenDocument,
user: QwenDocument,
workspace: QwenDocument,
system: QwenDocument,
use_workspace: bool,
) -> QwenDisableControl:
disabled = False
source: Optional[QwenDocument] = None
documents = [system_defaults, user]
if use_workspace:
documents.append(workspace)
documents.append(system)
for document in documents:
if document.disable_all_hooks is None:
continue
disabled = document.disable_all_hooks
source = document
return QwenDisableControl(disabled, source)
def _source_precondition(document: QwenDocument) -> FilePrecondition:
return FilePrecondition(
document.file_path,
qwen_document_label(document),
document.snapshot,
MAX_SOURCE_BYTES,
)
def _deduplicate_preconditions(
values: List[FilePrecondition],
) -> Tuple[FilePrecondition, ...]:
result: Dict[str, FilePrecondition] = {}
for value in values:
result.setdefault(_comparison_path(value.file_path), value)
return tuple(result.values())
def read_qwen_sources() -> QwenSources:
routing = _resolve_qwen_routing()
system_path = _system_settings_path()
workspace_path = os.path.join(os.getcwd(), ".qwen", "settings.json")
system = _read_document("system", system_path)
system_defaults = _read_document(
"system-defaults", _system_defaults_path(system_path)
)
user = _read_document(
"user", os.path.join(routing.qwen_home, "settings.json")
)
canonical_workspace = _canonical_path(os.getcwd())
canonical_home = _canonical_path(os.path.expanduser("~"))
workspace_active = _comparison_path(canonical_workspace) != _comparison_path(
canonical_home
)
workspace = (
_read_document("workspace", workspace_path)
if workspace_active
else create_qwen_document("workspace", workspace_path)
)
if workspace_active:
workspace_trusted, trust_precondition = _workspace_trust(
system, user, routing.qwen_home, canonical_workspace
)
else:
workspace_trusted, trust_precondition = False, None
validate_javascript_matchers([
system_defaults.hooks,
user.hooks,
workspace.hooks,
system.hooks,
])
preconditions = list(routing.preconditions)
preconditions.extend([
_source_precondition(system_defaults),
_source_precondition(user),
])
if workspace_active:
preconditions.append(_source_precondition(workspace))
preconditions.append(_source_precondition(system))
if trust_precondition is not None:
preconditions.append(trust_precondition)
return QwenSources(
qwen_home=routing.qwen_home,
system_defaults=system_defaults,
user=user,
workspace=workspace,
system=system,
workspace_active=workspace_active,
workspace_trusted=workspace_trusted,
disable_control=_effective_disable(
system_defaults,
user,
workspace,
system,
workspace_active and workspace_trusted,
),
preconditions=_deduplicate_preconditions(preconditions),
)
def require_qwen_hooks_enabled(sources: QwenSources) -> None:
if not sources.disable_control.disabled:
return
source = sources.disable_control.source
location = (
f"{qwen_document_label(source)} at {source.file_path}"
if source is not None
else "effective settings"
)
raise ValueError(
f"Qwen Code hooks are disabled by disableAllHooks in {location}"
)
+1 -1
View File
@@ -78,7 +78,7 @@ SUPPORTED_AGENTS: Dict[str, Dict[str, str]] = {
},
"qwen": {
"name": "Qwen Code",
"hook_event": "PreToolUse/PostToolUse",
"hook_event": "PreToolUse/PostToolUse/PostToolUseFailure",
"config_path": "~/.qwen/settings.json",
},
}