fix(claude): implement official Python hook contract

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 06:54:51 -04:00
1 parent a5a250ac94
commit 202aa1dff7
14 files changed
+2162 -198

No files matched your search

+87 -192
View File
@@ -1,210 +1,105 @@
"""Claude Code plugin — merges PostToolUse hook into ~/.claude/settings.json."""
"""Claude Code native user-hook integration."""
from __future__ import annotations
import json
import os
import sys
from ._file_io import write_json_atomic, write_text_atomic
from .base import AgentPlugin, InstallConfig, PluginStatus
from .hook_template import generate_hook_script
from .claudecode_contract import (
AGENT_KEY,
AUDIT_STATUS,
GUARD_STATUS,
ClaudeHooks,
build_claude_group,
claude_runtime_contracts,
remove_managed_claude_hooks,
render_claude_document,
)
from .claudecode_installation import (
commit_claude_installation,
commit_claude_uninstall,
preflight_claude_installation,
prepare_claude_installation,
prepare_claude_uninstall,
)
from .claudecode_io import (
claude_runtime_files_exist,
read_claude_document,
)
SETTINGS_PATH = os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
ELYDORA_DIR = os.path.join(os.path.expanduser("~"), ".elydora")
def _require_enabled_hooks(disabled: bool, file_path: str) -> None:
if disabled:
raise ValueError(
f"Claude Code hooks are disabled by disableAllHooks: {file_path}"
)
def _installed_hooks(
hooks: ClaudeHooks, guard_path: str, audit_path: str
) -> ClaudeHooks:
cleaned = remove_managed_claude_hooks(hooks)
return {
**cleaned,
"PreToolUse": [
*cleaned.get("PreToolUse", []),
build_claude_group(guard_path, GUARD_STATUS),
],
"PostToolUse": [
*cleaned.get("PostToolUse", []),
build_claude_group(audit_path, AUDIT_STATUS),
],
"PostToolUseFailure": [
*cleaned.get("PostToolUseFailure", []),
build_claude_group(audit_path, AUDIT_STATUS),
],
}
class ClaudeCodePlugin(AgentPlugin):
"""Install/uninstall Elydora audit hook for Claude Code."""
"""Install Elydora into Claude Code's native global user settings."""
@staticmethod
def _hook_path_for(agent_id: str) -> str:
return os.path.join(ELYDORA_DIR, agent_id, "hook.py")
manages_guard_runtime = True
def preflight_install(self, config: InstallConfig) -> None:
document = read_claude_document()
_require_enabled_hooks(document.hooks_disabled, document.file_path)
preflight_claude_installation(config, document)
def install(self, config: InstallConfig) -> None:
agent_id = config.get("agent_id", "")
agent_name = config.get("agent_name", "")
# Create per-agent directory
agent_dir = os.path.join(ELYDORA_DIR, agent_id)
os.makedirs(agent_dir, exist_ok=True)
# Write config.json
config_data = {
"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_name,
}
config_path = os.path.join(agent_dir, "config.json")
write_json_atomic(
config_path,
config_data,
0o600,
"Elydora runtime config",
document = read_claude_document()
_require_enabled_hooks(document.hooks_disabled, document.file_path)
paths = preflight_claude_installation(config, document)
rendered = render_claude_document(
document,
_installed_hooks(document.hooks, paths.guard_path, paths.audit_path),
)
# Write private key
private_key_path = os.path.join(agent_dir, "private.key")
write_text_atomic(
private_key_path,
config.get("private_key", ""),
0o600,
"Elydora private key",
changes = prepare_claude_installation(config, paths, rendered)
commit_claude_installation(changes)
print(
"Claude Code: global PreToolUse, PostToolUse, "
"and PostToolUseFailure hooks installed."
)
# Write the hook script
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"),
)
hook_path = self._hook_path_for(agent_id)
write_text_atomic(
hook_path,
script,
0o700,
"Elydora audit runtime",
)
guard_script_path = config.get("guard_script_path", "")
python_exe = sys.executable
# Merge into Claude Code settings
settings = _load_json(SETTINGS_PATH)
hooks = settings.setdefault("hooks", {})
# --- PreToolUse (guard — freeze enforcement) ---
pre_tool_use = hooks.setdefault("PreToolUse", [])
pre_tool_use[:] = [h for h in pre_tool_use if not _is_elydora_hook(h)]
if guard_script_path:
pre_tool_use.append({
"hooks": [
{
"type": "command",
"command": f'"{python_exe}" {guard_script_path}',
}
],
})
# --- PostToolUse (audit logging) ---
post_tool_use = hooks.setdefault("PostToolUse", [])
# Remove any existing Elydora hook entry
post_tool_use[:] = [h for h in post_tool_use if not _is_elydora_hook(h)]
post_tool_use.append({
"hooks": [
{
"type": "command",
"command": hook_path,
}
],
})
_save_json(SETTINGS_PATH, settings)
print("Elydora hook installed for Claude Code.")
print(f" Hook script: {hook_path}")
print(f" Settings: {SETTINGS_PATH}")
print(" Claude Code verification: run /hooks and claude doctor.")
def uninstall(self, agent_id: str = "") -> None:
# Remove hook entries from settings
if os.path.exists(SETTINGS_PATH):
settings = _load_json(SETTINGS_PATH)
hooks = settings.get("hooks", {})
changed = False
# Remove PreToolUse entries
pre_tool_use = hooks.get("PreToolUse", [])
pre_filtered = [h for h in pre_tool_use if not _is_elydora_hook(h, agent_id)]
if len(pre_filtered) != len(pre_tool_use):
hooks["PreToolUse"] = pre_filtered
if not pre_filtered:
del hooks["PreToolUse"]
changed = True
# Remove PostToolUse entries
post_tool_use = hooks.get("PostToolUse", [])
post_filtered = [h for h in post_tool_use if not _is_elydora_hook(h, agent_id)]
if len(post_filtered) != len(post_tool_use):
hooks["PostToolUse"] = post_filtered
if not post_filtered:
del hooks["PostToolUse"]
changed = True
if changed:
if not hooks:
del settings["hooks"]
_save_json(SETTINGS_PATH, settings)
# Hook script removal is handled by cli.py cmd_uninstall (rmtree of agent dir)
print("Elydora hook uninstalled from Claude Code.")
document = read_claude_document()
rendered = render_claude_document(
document,
remove_managed_claude_hooks(document.hooks, agent_id),
)
commit_claude_uninstall(prepare_claude_uninstall(rendered))
def status(self) -> PluginStatus:
# Scan ~/.elydora/*/hook.py for any installed hook
import glob as _glob
hook_pattern = os.path.join(ELYDORA_DIR, "*", "hook.py")
hook_files = _glob.glob(hook_pattern)
hook_exists = len(hook_files) > 0
settings_configured = False
if os.path.exists(SETTINGS_PATH):
settings = _load_json(SETTINGS_PATH)
hooks = settings.get("hooks", {})
pre_tool_use = hooks.get("PreToolUse", [])
post_tool_use = hooks.get("PostToolUse", [])
pre_configured = any(_is_elydora_hook(h) for h in pre_tool_use)
post_configured = any(_is_elydora_hook(h) for h in post_tool_use)
settings_configured = pre_configured and post_configured
installed = hook_exists and settings_configured
if installed:
details = f"Found {len(hook_files)} agent(s): {', '.join(hook_files)}"
elif hook_exists:
details = "Hook script exists but not configured in settings"
elif settings_configured:
details = "Configured in settings but hook script missing"
else:
details = "Not installed"
return PluginStatus(installed=installed, agent="claudecode", details=details)
def _is_elydora_hook(entry: dict, agent_id: str = "") -> bool:
# Collect all command strings from the entry
commands: list[str] = []
inner_hooks = entry.get("hooks")
if isinstance(inner_hooks, list):
for hook in inner_hooks:
if isinstance(hook, dict) and isinstance(hook.get("command"), str):
commands.append(hook["command"])
else:
command = entry.get("command")
if isinstance(command, str):
commands.append(command)
for cmd in commands:
cmd_lower = cmd.lower()
if "elydora" not in cmd_lower:
continue
# If agent_id is specified, only match hooks for that specific agent
if agent_id and agent_id in cmd:
return True
if not agent_id:
return True
return False
def _load_json(path: str) -> dict:
if not os.path.exists(path):
return {}
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def _save_json(path: str, data: dict) -> None:
write_json_atomic(path, data, 0o600, "Claude Code settings")
document = read_claude_document()
contracts = claude_runtime_contracts(document.hooks)
configured = not document.hooks_disabled and bool(contracts)
installed = configured and claude_runtime_files_exist(contracts)
details = (
f"Config: {document.file_path}"
if installed
else f"Configured at {document.file_path}; managed contract incomplete"
)
return PluginStatus(
installed=installed,
agent=AGENT_KEY,
details=details if configured else "Not installed",
)
+486
View File
@@ -0,0 +1,486 @@
"""Claude Code hook schema, ownership, and rendering."""
from __future__ import annotations
from dataclasses import dataclass
import json
import math
import os
import re
import sys
from typing import Any, Dict, List, Optional, Tuple
import urllib.parse
from ._strict_json import JsonObject, parse_json_object
AGENT_KEY = "claudecode"
CONFIG_FILE = "settings.json"
GUARD_SCRIPT = "guard.py"
AUDIT_SCRIPT = "hook.py"
HOOK_TIMEOUT_SECONDS = 10
GUARD_STATUS = "Checking Elydora agent state"
AUDIT_STATUS = "Recording Elydora tool use"
HOOK_EVENTS = frozenset({
"SessionStart", "Setup", "InstructionsLoaded", "UserPromptSubmit",
"UserPromptExpansion", "MessageDisplay", "PreToolUse",
"PermissionRequest", "PostToolUse", "PostToolUseFailure",
"PostToolBatch", "PermissionDenied", "Notification", "SubagentStart",
"SubagentStop", "TaskCreated", "TaskCompleted", "Stop", "StopFailure",
"TeammateIdle", "ConfigChange", "CwdChanged", "FileChanged",
"WorktreeCreate", "WorktreeRemove", "PreCompact", "PostCompact",
"SessionEnd", "Elicitation", "ElicitationResult",
})
COMMON_HANDLER_KEYS = frozenset({"if", "once", "statusMessage", "timeout"})
HANDLER_KEYS = {
"command": COMMON_HANDLER_KEYS | {
"args", "async", "asyncRewake", "command", "shell", "type",
},
"prompt": COMMON_HANDLER_KEYS | {
"continueOnBlock", "model", "prompt", "type",
},
"agent": COMMON_HANDLER_KEYS | {"model", "prompt", "type"},
"http": COMMON_HANDLER_KEYS | {
"allowedEnvVars", "headers", "type", "url",
},
"mcp_tool": COMMON_HANDLER_KEYS | {"input", "server", "tool", "type"},
}
_UNSET = object()
ClaudeHooks = Dict[str, List[JsonObject]]
@dataclass(frozen=True)
class ClaudeDocument:
exists: bool
file_path: str
root: JsonObject
hooks: ClaudeHooks
hooks_disabled: bool
raw: Optional[str] = None
@dataclass(frozen=True)
class RenderedClaudeDocument:
document: ClaudeDocument
changed: bool
next_source: Optional[str] = None
@dataclass(frozen=True)
class ClaudeRuntimeContract:
agent_id: str
guard_path: str
audit_path: str
@dataclass(frozen=True)
class _RuntimeReference:
agent_id: str
script_path: str
def runtime_root() -> str:
return os.path.join(os.path.expanduser("~"), ".elydora")
def same_claude_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def same_claude_agent_id(left: str, right: str) -> bool:
return os.path.normcase(left) == os.path.normcase(right)
def _require_known_keys(
value: JsonObject, allowed: frozenset[str], label: str
) -> None:
extra = next((key for key in value if key not in allowed), None)
if extra is not None:
raise ValueError(f'{label} contains unsupported field "{extra}"')
def _require_non_empty_string(value: Any, field: str, label: str) -> str:
if not isinstance(value, str) or not value:
raise ValueError(f'{label} field "{field}" must be a non-empty string')
return value
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 _optional_boolean(value: JsonObject, field: str, label: str) -> None:
if field in value and type(value[field]) is not bool:
raise ValueError(f'{label} field "{field}" must be a boolean')
def _validate_common_fields(value: JsonObject, label: str) -> None:
_optional_string(value, "if", label)
_optional_string(value, "statusMessage", label)
_optional_boolean(value, "once", label)
timeout = value.get("timeout")
if "timeout" in value and (
isinstance(timeout, bool)
or not isinstance(timeout, (int, float))
or not math.isfinite(float(timeout))
or float(timeout) <= 0
):
raise ValueError(f"{label} timeout must be a positive finite number")
def _string_array(value: Any, field: str, label: str) -> List[str]:
if not isinstance(value, list) or any(
not isinstance(item, str) for item in value
):
raise ValueError(f'{label} field "{field}" must be an array of strings')
return value
def _validate_handler(
value: Any, event: str, group_index: int, handler_index: int
) -> JsonObject:
label = (
f"Claude Code settings handler hooks.{event}[{group_index}]"
f".hooks[{handler_index}]"
)
if not isinstance(value, dict):
raise ValueError(f"{label} must be an object")
handler = dict(value)
handler_type = handler.get("type")
if not isinstance(handler_type, str) or handler_type not in HANDLER_KEYS:
raise ValueError(f'{label} has unsupported type "{handler_type}"')
_require_known_keys(handler, HANDLER_KEYS[handler_type], label)
_validate_common_fields(handler, label)
if handler_type == "command":
_require_non_empty_string(handler.get("command"), "command", label)
if "args" in handler:
_string_array(handler["args"], "args", label)
_optional_boolean(handler, "async", label)
_optional_boolean(handler, "asyncRewake", label)
if "shell" in handler and handler["shell"] not in ("bash", "powershell"):
raise ValueError(
f'{label} field "shell" must be "bash" or "powershell"'
)
elif handler_type in ("prompt", "agent"):
_require_non_empty_string(handler.get("prompt"), "prompt", label)
_optional_string(handler, "model", label)
if handler_type == "prompt":
_optional_boolean(handler, "continueOnBlock", label)
elif handler_type == "http":
raw_url = _require_non_empty_string(handler.get("url"), "url", label)
try:
parsed = urllib.parse.urlsplit(raw_url)
hostname = parsed.hostname
parsed.port
except ValueError as error:
raise ValueError(f'{label} field "url" must be a valid URL') from error
if parsed.scheme not in ("http", "https") or hostname is None:
raise ValueError(f'{label} field "url" must use HTTP or HTTPS')
headers = handler.get("headers")
if "headers" in handler and (
not isinstance(headers, dict)
or any(not isinstance(item, str) for item in headers.values())
):
raise ValueError(f'{label} field "headers" must map names to strings')
if "allowedEnvVars" in handler:
allowed = _string_array(
handler["allowedEnvVars"], "allowedEnvVars", label
)
if any(not item for item in allowed):
raise ValueError(
f'{label} field "allowedEnvVars" must contain non-empty strings'
)
else:
_require_non_empty_string(handler.get("server"), "server", label)
_require_non_empty_string(handler.get("tool"), "tool", label)
if "input" in handler and not isinstance(handler["input"], dict):
raise ValueError(f'{label} field "input" must be an object')
return handler
def _validate_group(value: Any, event: str, index: int) -> JsonObject:
label = f"Claude Code settings matcher group hooks.{event}[{index}]"
if not isinstance(value, dict):
raise ValueError(f"{label} must be an object")
group = dict(value)
_require_known_keys(group, frozenset({"hooks", "matcher"}), label)
if "matcher" in group and not isinstance(group["matcher"], str):
raise ValueError(f"{label} matcher must be a string")
handlers = group.get("hooks")
if not isinstance(handlers, list):
raise ValueError(f"{label} must contain a hooks array")
group["hooks"] = [
_validate_handler(handler, event, index, handler_index)
for handler_index, handler in enumerate(handlers)
]
return group
def _read_hooks(value: Any) -> ClaudeHooks:
if value is _UNSET:
return {}
if not isinstance(value, dict):
raise ValueError('Claude Code settings field "hooks" must be an object')
hooks: ClaudeHooks = {}
for event, groups in value.items():
if event not in HOOK_EVENTS:
raise ValueError(
f'Claude Code settings contains unsupported hook event "{event}"'
)
if not isinstance(groups, list):
raise ValueError(
f'Claude Code settings field "hooks.{event}" must be an array'
)
hooks[event] = [
_validate_group(group, event, index)
for index, group in enumerate(groups)
]
return hooks
def parse_claude_document(file_path: str, raw: str) -> ClaudeDocument:
root = parse_json_object(raw, f"Claude Code user settings at {file_path}")
disabled = root.get("disableAllHooks")
if "disableAllHooks" in root and type(disabled) is not bool:
raise ValueError(
'Claude Code settings field "disableAllHooks" must be a boolean'
)
return ClaudeDocument(
True,
file_path,
root,
_read_hooks(root.get("hooks", _UNSET)),
disabled is True,
raw,
)
def create_claude_document(file_path: str) -> ClaudeDocument:
return ClaudeDocument(False, file_path, {}, {}, False)
def build_claude_group(script_path: str, status_message: str) -> JsonObject:
return {
"hooks": [{
"type": "command",
"command": sys.executable,
"args": [script_path],
"timeout": HOOK_TIMEOUT_SECONDS,
"statusMessage": status_message,
}]
}
def _exact_managed_group(group: JsonObject) -> bool:
return set(group) == {"hooks"}
def _runtime_reference(
script_path: str, script_name: str
) -> Optional[_RuntimeReference]:
if not os.path.isabs(script_path) or os.path.basename(script_path) != script_name:
return None
agent_directory = os.path.dirname(script_path)
if not same_claude_path(os.path.dirname(agent_directory), runtime_root()):
return None
agent_id = os.path.basename(agent_directory)
if agent_id in ("", ".", ".."):
return None
return _RuntimeReference(agent_id, script_path)
def _legacy_reference(
command: Any, script_name: str
) -> Optional[_RuntimeReference]:
if not isinstance(command, str):
return None
if script_name == AUDIT_SCRIPT:
return _runtime_reference(command, script_name)
match = re.fullmatch(r'"([^"\r\n]+)" ([^\r\n]+)', command)
if (
match is None
or not os.path.isabs(match.group(1))
or not same_claude_path(match.group(1), sys.executable)
):
return None
return _runtime_reference(match.group(2), script_name)
def _managed_reference(
handler: JsonObject,
script_name: str,
status_message: str,
include_legacy: bool = False,
) -> Optional[_RuntimeReference]:
if (
set(handler) == {"args", "command", "statusMessage", "timeout", "type"}
and handler.get("type") == "command"
and type(handler.get("timeout")) is int
and handler.get("timeout") == HOOK_TIMEOUT_SECONDS
and handler.get("statusMessage") == status_message
and isinstance(handler.get("command"), str)
and os.path.isabs(str(handler["command"]))
and same_claude_path(str(handler["command"]), sys.executable)
and isinstance(handler.get("args"), list)
and len(handler["args"]) == 1
and isinstance(handler["args"][0], str)
):
return _runtime_reference(handler["args"][0], script_name)
if (
include_legacy
and set(handler) == {"command", "type"}
and handler.get("type") == "command"
):
return _legacy_reference(handler.get("command"), script_name)
return None
def _remove_from_groups(
groups: List[JsonObject],
script_name: str,
status_message: str,
agent_id: str,
) -> Tuple[List[JsonObject], bool]:
result: List[JsonObject] = []
removed = False
for group in groups:
kept = []
for handler in group["hooks"]:
reference = _managed_reference(
handler, script_name, status_message, True
)
owned = reference is not None and (
not agent_id
or same_claude_agent_id(reference.agent_id, agent_id)
)
if owned:
removed = True
else:
kept.append(handler)
if kept:
result.append({**group, "hooks": kept})
elif not _exact_managed_group(group):
result.append({**group, "hooks": []})
return result, removed
def remove_managed_claude_hooks(
hooks: ClaudeHooks, agent_id: str = ""
) -> ClaudeHooks:
result = {event: list(groups) for event, groups in hooks.items()}
for event, script_name, status_message in (
("PreToolUse", GUARD_SCRIPT, GUARD_STATUS),
("PostToolUse", AUDIT_SCRIPT, AUDIT_STATUS),
("PostToolUseFailure", AUDIT_SCRIPT, AUDIT_STATUS),
):
groups, removed = _remove_from_groups(
result.get(event, []), script_name, status_message, agent_id
)
if not removed:
continue
if groups:
result[event] = groups
else:
result.pop(event, None)
return result
def _managed_event(event: str) -> Optional[Tuple[str, str]]:
if event == "PreToolUse":
return GUARD_SCRIPT, GUARD_STATUS
if event in ("PostToolUse", "PostToolUseFailure"):
return AUDIT_SCRIPT, AUDIT_STATUS
return None
def _entirely_managed(document: ClaudeDocument) -> bool:
if not document.exists or set(document.root) != {"hooks"} or not document.hooks:
return False
handlers = 0
for event, groups in document.hooks.items():
contract = _managed_event(event)
if contract is None or not groups:
return False
for group in groups:
if (
not _exact_managed_group(group)
or not group["hooks"]
or any(
_managed_reference(handler, contract[0], contract[1], True)
is None
for handler in group["hooks"]
)
):
return False
handlers += len(group["hooks"])
return handlers > 0
def render_claude_document(
document: ClaudeDocument, hooks: ClaudeHooks
) -> RenderedClaudeDocument:
if hooks == document.hooks:
return RenderedClaudeDocument(document, False)
if not document.exists and not hooks:
return RenderedClaudeDocument(document, False)
if not hooks and _entirely_managed(document):
return RenderedClaudeDocument(document, True)
root = dict(document.root)
if hooks:
root["hooks"] = hooks
else:
root.pop("hooks", None)
next_source = json.dumps(root, indent=2, ensure_ascii=False) + "\n"
parse_claude_document(document.file_path, next_source)
return RenderedClaudeDocument(
document, next_source != document.raw, next_source
)
def _references_for_event(
groups: List[JsonObject], script_name: str, status_message: str
) -> Dict[str, List[_RuntimeReference]]:
result: Dict[str, List[_RuntimeReference]] = {}
for group in groups:
if not _exact_managed_group(group):
continue
for handler in group["hooks"]:
reference = _managed_reference(handler, script_name, status_message)
if reference is not None:
result.setdefault(
os.path.normcase(reference.agent_id), []
).append(reference)
return result
def claude_runtime_contracts(
hooks: ClaudeHooks,
) -> List[ClaudeRuntimeContract]:
guards = _references_for_event(
hooks.get("PreToolUse", []), GUARD_SCRIPT, GUARD_STATUS
)
successes = _references_for_event(
hooks.get("PostToolUse", []), AUDIT_SCRIPT, AUDIT_STATUS
)
failures = _references_for_event(
hooks.get("PostToolUseFailure", []), AUDIT_SCRIPT, AUDIT_STATUS
)
contracts = []
for key, guard in guards.items():
success = successes.get(key, [])
failure = failures.get(key, [])
if len(guard) != 1 or len(success) != 1 or len(failure) != 1:
continue
if not same_claude_path(success[0].script_path, failure[0].script_path):
continue
contracts.append(ClaudeRuntimeContract(
guard[0].agent_id,
guard[0].script_path,
success[0].script_path,
))
return contracts
+167
View File
@@ -0,0 +1,167 @@
"""Transactional Claude Code hook and runtime installation."""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from typing import List, Optional
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, file_change, write_changes
from .base import InstallConfig
from .claudecode_contract import (
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
ClaudeDocument,
RenderedClaudeDocument,
runtime_root,
same_claude_path,
)
from .claudecode_io import (
rendered_change,
validate_api_origin,
validate_private_key,
validate_runtime_tree,
)
from .hook_template import generate_guard_script, generate_hook_script
@dataclass(frozen=True)
class ClaudeRuntimePaths:
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) -> ClaudeRuntimePaths:
agent_id = config.get("agent_id", "")
if not agent_id:
raise ValueError("agent_id is required")
agent_directory = resolve_agent_directory(runtime_root(), agent_id)
guard_path = os.path.join(agent_directory, GUARD_SCRIPT)
audit_path = os.path.join(agent_directory, AUDIT_SCRIPT)
if not same_claude_path(config.get("guard_script_path", ""), guard_path):
raise ValueError(
"Elydora guard runtime must use the managed agent directory: "
f"{guard_path}"
)
return ClaudeRuntimePaths(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"Claude 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_claude_installation(
config: InstallConfig, document: ClaudeDocument
) -> ClaudeRuntimePaths:
if not document.file_path:
raise ValueError("Claude Code installation requires a settings path")
_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 _present(changes: List[Optional[FileChange]]) -> List[FileChange]:
return [change for change in changes if change is not None]
def prepare_claude_installation(
config: InstallConfig,
paths: ClaudeRuntimePaths,
rendered: RenderedClaudeDocument,
) -> 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 commit_claude_installation(changes: List[FileChange]) -> None:
write_changes(changes, "Install Claude Code hooks")
def prepare_claude_uninstall(
rendered: RenderedClaudeDocument,
) -> List[FileChange]:
return _present([rendered_change(rendered)])
def commit_claude_uninstall(changes: List[FileChange]) -> None:
write_changes(changes, "Uninstall Claude Code hooks")
+246
View File
@@ -0,0 +1,246 @@
"""Claude Code settings discovery and managed runtime I/O."""
from __future__ import annotations
import base64
import os
from typing import Any, List, Optional
import urllib.parse
from ._managed_files import (
MAX_CONFIG_BYTES,
MAX_SECRET_BYTES,
MAX_SOURCE_BYTES,
physical_directory_exists,
physical_file_exists,
read_physical_file,
)
from ._strict_json import JsonObject, parse_json_object
from ._transaction import FileChange, source_change, write_changes
from .claudecode_contract import (
AGENT_KEY,
CONFIG_FILE,
ClaudeDocument,
ClaudeRuntimeContract,
RenderedClaudeDocument,
create_claude_document,
parse_claude_document,
runtime_root,
same_claude_agent_id,
same_claude_path,
)
def claude_config_directory() -> str:
if "CLAUDE_CONFIG_DIR" not in os.environ:
return os.path.join(os.path.expanduser("~"), ".claude")
return os.path.abspath(os.environ["CLAUDE_CONFIG_DIR"])
def claude_settings_path() -> str:
return os.path.join(claude_config_directory(), CONFIG_FILE)
def read_claude_document() -> ClaudeDocument:
file_path = claude_settings_path()
physical_directory_exists(
os.path.dirname(file_path), "Claude Code configuration directory"
)
snapshot = read_physical_file(
file_path, "Claude Code user settings", MAX_SOURCE_BYTES
)
if snapshot is None:
return create_claude_document(file_path)
return parse_claude_document(file_path, snapshot.contents)
def rendered_change(
rendered: RenderedClaudeDocument,
) -> Optional[FileChange]:
if not rendered.changed:
return None
return source_change(
rendered.document.file_path,
"Claude Code user settings",
rendered.document.raw,
rendered.next_source,
0o600,
MAX_SOURCE_BYTES,
)
def write_claude_document(rendered: RenderedClaudeDocument) -> None:
change = rendered_change(rendered)
if change is not None:
write_changes([change], "Uninstall Claude Code hooks")
def validate_api_origin(value: str, label: str = "base_url") -> None:
try:
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"{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 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 {field} is invalid: {config_path}"
)
return value
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}'
)
_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_claude_agent_id(agent_id, expected_agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
"Elydora runtime identity does not match Claude 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")
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 = runtime_root()
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_states = [
physical_file_exists(os.path.join(agent_directory, name), label)
for name, label in artifacts
]
artifact_exists = any(artifact_states)
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_claude_agent_id(configured_id, agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
"Elydora runtime config identity does not match Claude Code agent "
f"{agent_id}: {config_path}"
)
def _runtime_contract_exists(contract: ClaudeRuntimeContract) -> bool:
root = runtime_root()
agent_directory = os.path.dirname(contract.guard_path)
if (
not same_claude_path(os.path.dirname(agent_directory), root)
or not same_claude_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")
return bool(guard.contents) and bool(audit.contents)
def claude_runtime_files_exist(
contracts: List[ClaudeRuntimeContract],
) -> bool:
return any(_runtime_contract_exists(contract) for contract in contracts)
+2 -2
View File
@@ -13,8 +13,8 @@ SUPPORTED_AGENTS: Dict[str, Dict[str, str]] = {
},
"claudecode": {
"name": "Claude Code",
"hook_event": "PostToolUse",
"config_path": "~/.claude/settings.json",
"hook_event": "PreToolUse/PostToolUse/PostToolUseFailure",
"config_path": "$CLAUDE_CONFIG_DIR/settings.json",
},
"codex": {
"name": "OpenAI Codex",