fix(grok): implement official hook contract

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 05:38:40 -04:00
1 parent 978e15e251
commit a5a250ac94
17 files changed
+2175 -785

No files matched your search

+15 -3
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import json
from typing import Any, Dict, List, Tuple
from typing import Any, Dict, List, NoReturn, Tuple
JsonObject = Dict[str, Any]
@@ -13,6 +13,10 @@ class _DuplicateKey(ValueError):
pass
class _InvalidConstant(ValueError):
pass
def _unique_object(pairs: List[Tuple[str, Any]]) -> JsonObject:
result: JsonObject = {}
for key, value in pairs:
@@ -22,10 +26,18 @@ def _unique_object(pairs: List[Tuple[str, Any]]) -> JsonObject:
return result
def _reject_constant(value: str) -> NoReturn:
raise _InvalidConstant(f'invalid numeric constant "{value}"')
def parse_json_object(raw: str, label: str) -> JsonObject:
try:
value = json.loads(raw, object_pairs_hook=_unique_object)
except (_DuplicateKey, json.JSONDecodeError) as error:
value = json.loads(
raw,
object_pairs_hook=_unique_object,
parse_constant=_reject_constant,
)
except (_DuplicateKey, _InvalidConstant, json.JSONDecodeError) as error:
raise ValueError(f"Failed to parse {label}: {error}") from error
if not isinstance(value, dict):
raise ValueError(f"{label} must contain a JSON object")
+79 -7
View File
@@ -9,6 +9,7 @@ from typing import List, Optional, Sequence
from uuid import uuid4
from ._managed_files import (
FileSnapshot,
MAX_SOURCE_BYTES,
ensure_physical_directory,
physical_file_exists,
@@ -34,6 +35,7 @@ class _StagedChange:
change: FileChange
temporary_path: Optional[str]
rollback_path: Optional[str]
committed_snapshot: Optional[FileSnapshot] = None
committed: bool = False
@@ -56,6 +58,13 @@ def source_change(
) -> Optional[FileChange]:
if original == next_source:
return None
if (
next_source is not None
and len(next_source.encode("utf-8")) > maximum_bytes
):
raise ValueError(
f"{label} exceeds {maximum_bytes} bytes: {file_path}"
)
snapshot = read_physical_file(file_path, label, maximum_bytes)
current = None if snapshot is None else snapshot.contents
if current != original:
@@ -212,17 +221,80 @@ def _commit(staged: _StagedChange) -> None:
raise OSError(f"Missing staged file for {staged.change.label}")
os.replace(staged.temporary_path, staged.change.file_path)
staged.committed = True
current = read_physical_file(
staged.change.file_path,
staged.change.label,
staged.change.maximum_bytes,
)
if staged.change.next_source is None:
if current is not None:
raise OSError(
f"{staged.change.label} remained after removal: "
f"{staged.change.file_path}"
)
return
if current is None or current.contents != staged.change.next_source:
raise OSError(
f"{staged.change.label} changed immediately after commit: "
f"{staged.change.file_path}"
)
staged.committed_snapshot = current
def _assert_committed_unchanged(staged: _StagedChange) -> None:
current = read_physical_file(
staged.change.file_path,
staged.change.label,
staged.change.maximum_bytes,
)
if staged.change.next_source is None:
if current is not None:
raise OSError(
f"{staged.change.label} changed during transaction recovery: "
f"{staged.change.file_path}"
)
return
committed = staged.committed_snapshot
if current is None or committed is None or (
current.contents != committed.contents
or current.device != committed.device
or current.inode != committed.inode
):
raise OSError(
f"{staged.change.label} changed during transaction recovery: "
f"{staged.change.file_path}"
)
def _preserve_rollback(staged: _StagedChange, error: Exception) -> OSError:
if staged.rollback_path is None:
return error if isinstance(error, OSError) else OSError(str(error))
rollback_path = staged.rollback_path
staged.rollback_path = None
return OSError(
f"{error}; original content preserved at {rollback_path}"
)
def _rollback(staged: _StagedChange) -> None:
if not staged.committed:
return
if staged.change.original is None:
_remove_optional(staged.change.file_path)
return
if staged.rollback_path is None:
raise OSError(f"Missing rollback data for {staged.change.label}")
os.replace(staged.rollback_path, staged.change.file_path)
try:
_assert_committed_unchanged(staged)
except Exception as error:
raise _preserve_rollback(staged, error) from error
try:
if staged.change.next_source is None or staged.change.original is not None:
if staged.rollback_path is None:
raise OSError(
f"Missing rollback data for {staged.change.label}"
)
os.replace(staged.rollback_path, staged.change.file_path)
staged.rollback_path = None
else:
_remove_optional(staged.change.file_path)
except Exception as error:
raise _preserve_rollback(staged, error) from error
def _cleanup(staged: _StagedChange) -> None:
@@ -248,7 +320,7 @@ def write_changes(changes: Sequence[FileChange], label: str) -> None:
for item in reversed(staged):
try:
_rollback(item)
except OSError as rollback_error:
except Exception as rollback_error:
recovery_errors.append(str(rollback_error))
for item in staged:
try:
+1
View File
@@ -178,6 +178,7 @@ class CursorPlugin(AgentPlugin):
agent_id,
success_output='{"permission":"allow"}\n',
fail_closed=True,
deny_protocol="cursor",
)
changes = _present([
runtime_change(
+65 -402
View File
@@ -2,425 +2,88 @@
from __future__ import annotations
from dataclasses import dataclass
import math
import os
import shlex
# subprocess provides argument quoting only; this module starts no process.
import subprocess # nosec B404
import sys
from typing import Any, Dict, List, Optional, Tuple
from ._file_io import (
read_json as _read_json,
regular_file_exists as _regular_file_exists,
remove_file as _remove_file,
require_runtime as _require_runtime,
write_json_atomic as _write_json_atomic,
write_text_atomic as _write_text_atomic,
)
from .base import AgentPlugin, InstallConfig, PluginStatus
from .hook_template import generate_hook_script
from .grok_contract import (
AGENT_KEY,
GrokHooks,
build_grok_group,
grok_runtime_contracts,
remove_managed_grok_hooks,
render_grok_document,
)
from .grok_installation import (
commit_grok_installation,
commit_grok_uninstall,
preflight_grok_installation,
prepare_grok_installation,
prepare_grok_uninstall,
)
from .grok_io import grok_runtime_files_exist, read_grok_document
AGENT_KEY = "grok"
GUARD_SCRIPT = "guard.py"
AUDIT_SCRIPT = "hook.py"
HOOK_TIMEOUT_SECONDS = 10
CONFIG_FILE = "elydora-audit.json"
ELYDORA_DIR = os.path.join(os.path.expanduser("~"), ".elydora")
JsonObject = Dict[str, Any]
GrokHooks = Dict[str, List[JsonObject]]
@dataclass(frozen=True)
class GrokDocument:
exists: bool
config_path: str
root: JsonObject
hooks: GrokHooks
@dataclass(frozen=True)
class RuntimeContract:
agent_id: str
guard_path: str
audit_path: str
def _home_dir() -> str:
return os.path.expanduser("~")
def _resolve_config_path() -> str:
grok_home = os.environ.get("GROK_HOME") or os.path.join(_home_dir(), ".grok")
return os.path.join(grok_home, "hooks", CONFIG_FILE)
def _build_command(script_path: str) -> str:
arguments = [sys.executable, script_path]
return (
subprocess.list2cmdline(arguments)
if os.name == "nt"
else shlex.join(arguments)
)
def _build_handler(script_path: str) -> JsonObject:
def _installed_hooks(
hooks: GrokHooks, guard_path: str, audit_path: str
) -> GrokHooks:
cleaned = remove_managed_grok_hooks(hooks)
return {
"type": "command",
"command": _build_command(script_path),
"timeout": HOOK_TIMEOUT_SECONDS,
**cleaned,
"PreToolUse": [
*cleaned.get("PreToolUse", []),
build_grok_group(guard_path),
],
"PostToolUse": [
*cleaned.get("PostToolUse", []),
build_grok_group(audit_path),
],
"PostToolUseFailure": [
*cleaned.get("PostToolUseFailure", []),
build_grok_group(audit_path),
],
}
def _parse_generated_command(command: str) -> Optional[Tuple[str, str]]:
try:
arguments = shlex.split(command, posix=os.name != "nt")
except ValueError:
return None
if os.name == "nt":
arguments = [
value[1:-1]
if len(value) >= 2 and value.startswith('"') and value.endswith('"')
else value
for value in arguments
]
if len(arguments) != 2 or not arguments[0] or not arguments[1]:
return None
return arguments[0], arguments[1]
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 (
handler.get("type") != "command"
or handler.get("timeout") != HOOK_TIMEOUT_SECONDS
or not isinstance(handler.get("command"), str)
):
return None
parsed = _parse_generated_command(str(handler["command"]))
if parsed is None:
return None
script_path = parsed[1]
if os.path.normcase(os.path.basename(script_path)) != os.path.normcase(script_name):
return None
agent_dir = os.path.dirname(script_path)
if not _same_path(os.path.dirname(agent_dir), ELYDORA_DIR):
return None
agent_id = os.path.basename(agent_dir)
return agent_id if agent_id not in {"", ".", ".."} else None
def _validate_handler(
value: Any,
event: str,
group_index: int,
handler_index: int,
) -> JsonObject:
label = (
f"Grok hooks config 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 handler_type not in ("command", "http"):
raise ValueError(f'{label} has unsupported type "{handler_type}"')
if handler_type == "command" and (
not isinstance(handler.get("command"), str) or not handler["command"]
):
raise ValueError(f"{label} requires a non-empty command")
if handler_type == "http" and (
not isinstance(handler.get("url"), str) or not handler["url"]
):
raise ValueError(f"{label} requires a non-empty url")
timeout = handler.get("timeout")
if timeout is not None and (
isinstance(timeout, bool)
or not isinstance(timeout, (int, float))
or not math.isfinite(timeout)
or timeout <= 0
):
raise ValueError(f"{label} timeout must be a positive number")
return handler
def _validate_group(value: Any, event: str, group_index: int) -> JsonObject:
label = f"Grok hooks config group hooks.{event}[{group_index}]"
if not isinstance(value, dict):
raise ValueError(f"{label} must be an object")
group = dict(value)
matcher = group.get("matcher")
if "matcher" in group and not isinstance(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, group_index, handler_index)
for handler_index, handler in enumerate(handlers)
]
return group
def _read_hooks(root: JsonObject) -> GrokHooks:
if "hooks" not in root:
return {}
raw_hooks = root["hooks"]
if not isinstance(raw_hooks, dict):
raise ValueError('Grok hooks config field "hooks" must be an object')
hooks: GrokHooks = {}
for event, groups in raw_hooks.items():
if not isinstance(groups, list):
raise ValueError(
f'Grok hooks config field "hooks.{event}" must be an array'
)
hooks[event] = [
_validate_group(group, event, group_index)
for group_index, group in enumerate(groups)
]
return hooks
def _read_config() -> GrokDocument:
config_path = _resolve_config_path()
root = _read_json(config_path, "Grok hooks config")
if root is None:
return GrokDocument(False, config_path, {}, {})
return GrokDocument(True, config_path, root, _read_hooks(root))
def _remove_managed(
groups: List[JsonObject],
script_name: str,
agent_id: str = "",
) -> Tuple[List[JsonObject], bool]:
result: List[JsonObject] = []
changed = False
for group in groups:
if "matcher" in group:
result.append(group)
continue
handlers = group["hooks"]
kept: List[JsonObject] = []
group_changed = False
for handler in handlers:
managed_id = _managed_agent_id(handler, script_name)
remove = managed_id is not None and (
not agent_id or _same_agent_id(managed_id, agent_id)
)
if remove:
changed = True
group_changed = True
else:
kept.append(handler)
if not group_changed:
result.append(group)
elif kept:
result.append({**group, "hooks": kept})
return result, changed
def _remove_managed_hooks(
hooks: GrokHooks,
agent_id: str = "",
) -> Tuple[GrokHooks, bool]:
result = dict(hooks)
changed = False
for event, script_name in (
("PreToolUse", GUARD_SCRIPT),
("PostToolUse", AUDIT_SCRIPT),
):
groups, event_changed = _remove_managed(
result.get(event, []), script_name, agent_id
)
if not event_changed:
continue
changed = True
if groups:
result[event] = groups
else:
result.pop(event, None)
return result, changed
def _managed_ids(groups: List[JsonObject], script_name: str) -> Dict[str, str]:
result: Dict[str, str] = {}
for group in groups:
if "matcher" in group:
continue
for handler in group["hooks"]:
agent_id = _managed_agent_id(handler, script_name)
if agent_id:
result[os.path.normcase(agent_id)] = agent_id
return result
def _runtime_contracts(hooks: GrokHooks) -> List[RuntimeContract]:
guards = _managed_ids(hooks.get("PreToolUse", []), GUARD_SCRIPT)
audits = _managed_ids(hooks.get("PostToolUse", []), AUDIT_SCRIPT)
contracts: List[RuntimeContract] = []
for normalized_id in sorted(set(guards) & set(audits)):
agent_id = guards[normalized_id]
contracts.append(RuntimeContract(
agent_id=agent_id,
guard_path=os.path.join(ELYDORA_DIR, agent_id, GUARD_SCRIPT),
audit_path=os.path.join(ELYDORA_DIR, agent_id, AUDIT_SCRIPT),
))
return contracts
def _runtime_scripts_exist(contracts: List[RuntimeContract]) -> bool:
try:
with os.scandir(ELYDORA_DIR) as iterator:
entries = sorted(iterator, key=lambda entry: entry.name)
except FileNotFoundError:
return False
except OSError as error:
raise OSError(f"Read Elydora runtime directory at {ELYDORA_DIR}: {error}") from error
for contract in contracts:
entry = next(
(
candidate
for candidate in entries
if _same_agent_id(candidate.name, contract.agent_id)
),
None,
)
if entry is None:
continue
try:
if not entry.is_dir(follow_symlinks=False):
continue
except OSError as error:
raise OSError(f"Read Elydora runtime entry at {entry.path}: {error}") from error
runtime_config_path = os.path.join(entry.path, "config.json")
runtime_config = _read_json(runtime_config_path, "Elydora runtime config")
if runtime_config is None:
continue
agent_name = runtime_config.get("agent_name")
if not isinstance(agent_name, str):
raise ValueError(
f'Elydora runtime config at {runtime_config_path} field '
'"agent_name" must be a string'
)
if agent_name != AGENT_KEY:
continue
guard_path = os.path.join(entry.path, GUARD_SCRIPT)
audit_path = os.path.join(entry.path, AUDIT_SCRIPT)
return _regular_file_exists(
guard_path, "Elydora guard runtime"
) and _regular_file_exists(audit_path, "Elydora audit runtime")
return False
class GrokPlugin(AgentPlugin):
"""Install Elydora into Grok Build's native global user hooks."""
manages_guard_runtime = True
def preflight_install(self, config: InstallConfig) -> None:
document = read_grok_document()
preflight_grok_installation(config, document)
def install(self, config: InstallConfig) -> None:
agent_id = config.get("agent_id", "")
if not agent_id:
raise ValueError("agent_id is required")
source = _read_config()
guard_path = config.get("guard_script_path", "")
_require_runtime(guard_path, "Elydora guard runtime")
agent_dir = os.path.join(ELYDORA_DIR, agent_id)
audit_path = os.path.join(agent_dir, AUDIT_SCRIPT)
cleaned, _ = _remove_managed_hooks(source.hooks)
hooks: GrokHooks = {
**cleaned,
"PreToolUse": [
*cleaned.get("PreToolUse", []),
{"hooks": [_build_handler(guard_path)]},
],
"PostToolUse": [
*cleaned.get("PostToolUse", []),
{"hooks": [_build_handler(audit_path)]},
],
}
runtime_config: JsonObject = {
"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"),
document = read_grok_document()
paths = preflight_grok_installation(config, document)
rendered = render_grok_document(
document,
_installed_hooks(document.hooks, paths.guard_path, paths.audit_path),
)
_write_json_atomic(
os.path.join(agent_dir, "config.json"),
runtime_config,
0o600,
"Elydora runtime config",
changes = prepare_grok_installation(config, paths, rendered)
commit_grok_installation(changes)
print(
"Grok Build: global PreToolUse, PostToolUse, "
"and PostToolUseFailure hooks installed."
)
_write_text_atomic(
os.path.join(agent_dir, "private.key"),
config.get("private_key", ""),
0o600,
"Elydora private key",
)
_write_text_atomic(audit_path, audit_script, 0o700, "Elydora audit runtime")
_write_json_atomic(
source.config_path,
{**source.root, "hooks": hooks},
0o600,
"Grok hooks config",
)
print("Grok Build: global PreToolUse and PostToolUse hooks installed.")
def uninstall(self, agent_id: str = "") -> None:
source = _read_config()
if not source.exists:
return
hooks, changed = _remove_managed_hooks(source.hooks, agent_id)
if not changed:
return
root = dict(source.root)
if hooks:
root["hooks"] = hooks
else:
root.pop("hooks", None)
if root:
_write_json_atomic(
source.config_path,
root,
0o600,
"Grok hooks config",
)
else:
_remove_file(source.config_path, "Grok hooks config")
document = read_grok_document()
rendered = render_grok_document(
document,
remove_managed_grok_hooks(document.hooks, agent_id),
)
commit_grok_uninstall(prepare_grok_uninstall(rendered))
def status(self) -> PluginStatus:
source = _read_config()
contracts = _runtime_contracts(source.hooks)
if not contracts:
return PluginStatus(
installed=False,
agent=AGENT_KEY,
details="Not installed",
)
installed = _runtime_scripts_exist(contracts)
document = read_grok_document()
contracts = grok_runtime_contracts(document.hooks)
installed = bool(contracts) and grok_runtime_files_exist(contracts)
details = (
f"Config: {source.config_path}"
f"Config: {document.config_path}"
if installed
else f"Configured at {source.config_path}; runtime scripts missing"
else f"Configured at {document.config_path}; managed contract incomplete"
)
return PluginStatus(
installed=installed,
agent=AGENT_KEY,
details=details if contracts else "Not installed",
)
return PluginStatus(installed=installed, agent=AGENT_KEY, details=details)
+232
View File
@@ -0,0 +1,232 @@
"""Grok hook command rendering and exact runtime ownership."""
from __future__ import annotations
import base64
from dataclasses import dataclass
import ntpath
import os
import re
import shlex
import subprocess # nosec B404 - used only for legacy command rendering
import sys
from typing import Optional, Tuple
@dataclass(frozen=True)
class GrokRuntimeReference:
agent_id: str
script_path: str
@dataclass(frozen=True)
class _ParsedArgument:
value: str
next_index: int
def runtime_root() -> str:
return os.path.join(os.path.expanduser("~"), ".elydora")
def same_grok_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def same_grok_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 _windows_powershell_path() -> str:
configured = os.environ.get("SystemRoot") if os.name == "nt" else None
system_root = (
configured
if configured
and ntpath.isabs(configured)
and re.search(r'["%\r\n]', configured) is None
else r"C:\Windows"
)
return ntpath.join(
system_root,
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe",
)
def _windows_command(script_path: str) -> str:
source = (
f"& {_quote_powershell(sys.executable)} "
f"{_quote_powershell(script_path)}; exit $LASTEXITCODE"
)
encoded = base64.b64encode(source.encode("utf-16le")).decode("ascii")
return (
f'"{_windows_powershell_path()}" -NoLogo -NoProfile '
f"-NonInteractive -EncodedCommand {encoded}"
)
def build_grok_command(script_path: str) -> str:
if not os.path.isabs(sys.executable) or not os.path.isabs(script_path):
raise ValueError(
"Grok hook commands require absolute executable and script paths"
)
if os.name == "nt":
return _windows_command(script_path)
return f"{_quote_posix(sys.executable)} {_quote_posix(script_path)}"
def _read_posix_argument(command: str, start: int) -> Optional[_ParsedArgument]:
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 _ParsedArgument(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 command[executable.next_index : executable.next_index + 1] != " ":
return None
script = _read_posix_argument(command, executable.next_index + 1)
if script is None or script.next_index != len(command):
return None
return executable.value, script.value
def _read_powershell_argument(
command: str, start: int
) -> Optional[_ParsedArgument]:
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 _ParsedArgument(value, index + 1)
return None
def _parse_powershell_source(source: str) -> Optional[Tuple[str, str]]:
if not source.startswith("& "):
return None
executable = _read_powershell_argument(source, 2)
if executable is None or source[executable.next_index : executable.next_index + 1] != " ":
return None
script = _read_powershell_argument(source, executable.next_index + 1)
if script is None or source[script.next_index :] != "; exit $LASTEXITCODE":
return None
return executable.value, script.value
def _parse_windows_command(command: str) -> Optional[Tuple[str, str]]:
match = re.fullmatch(
r'"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive '
r"-EncodedCommand ([A-Za-z0-9+/]+={0,2})",
command,
)
if (
match is None
or not ntpath.isabs(match.group(1))
or ntpath.basename(match.group(1)).lower() != "powershell.exe"
):
return None
try:
raw = base64.b64decode(match.group(2), validate=True)
if base64.b64encode(raw).decode("ascii") != match.group(2):
return None
source = raw.decode("utf-16le")
except (UnicodeDecodeError, ValueError):
return None
return _parse_powershell_source(source)
def _parse_legacy_posix_command(command: str) -> Optional[Tuple[str, str]]:
try:
arguments = shlex.split(command, posix=True)
except ValueError:
return None
if len(arguments) != 2 or shlex.join(arguments) != command:
return None
return arguments[0], arguments[1]
def _parse_legacy_windows_command(command: str) -> Optional[Tuple[str, str]]:
match = re.fullmatch(
r'(?:(?:"([^"\r\n]+)")|([^\s"\r\n]+)) '
r'(?:(?:"([^"\r\n]+)")|([^\s"\r\n]+))',
command,
)
if match is None:
return None
arguments = [match.group(1) or match.group(2), match.group(3) or match.group(4)]
if subprocess.list2cmdline(arguments) != command:
return None
return arguments[0], arguments[1]
def _is_python_executable(file_path: str) -> bool:
return (
re.fullmatch(
r"python(?:[0-9]+(?:\.[0-9]+)*)?(?:\.exe)?",
os.path.basename(file_path),
re.IGNORECASE,
)
is not None
)
def grok_runtime_reference(
command: str, script_name: str
) -> Optional[GrokRuntimeReference]:
parsed = (
_parse_posix_command(command)
or _parse_windows_command(command)
or _parse_legacy_posix_command(command)
or _parse_legacy_windows_command(command)
)
if parsed is None:
return None
executable, script_path = parsed
if (
not os.path.isabs(executable)
or not os.path.isabs(script_path)
or not _is_python_executable(executable)
or os.path.basename(script_path) != script_name
):
return None
agent_directory = os.path.dirname(script_path)
if not same_grok_path(os.path.dirname(agent_directory), runtime_root()):
return None
agent_id = os.path.basename(agent_directory)
if agent_id in {"", ".", ".."}:
return None
return GrokRuntimeReference(agent_id, script_path)
+296
View File
@@ -0,0 +1,296 @@
"""Grok hook schema, exact ownership, and JSON rendering."""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from typing import Any, Dict, List, Optional, Tuple
from ._strict_json import JsonObject, parse_json_object
from .grok_command import (
GrokRuntimeReference,
build_grok_command,
grok_runtime_reference,
same_grok_agent_id,
same_grok_path,
)
AGENT_KEY = "grok"
GUARD_SCRIPT = "guard.py"
AUDIT_SCRIPT = "hook.py"
HOOK_TIMEOUT_SECONDS = 10
MATCHER_REJECTING_EVENTS = frozenset(
{"SessionStart", "SessionEnd", "Stop", "UserPromptSubmit"}
)
GrokHooks = Dict[str, List[JsonObject]]
@dataclass(frozen=True)
class GrokDocument:
exists: bool
config_path: str
root: JsonObject
hooks: GrokHooks
raw: Optional[str] = None
@dataclass(frozen=True)
class RenderedGrokDocument:
document: GrokDocument
changed: bool
next_source: Optional[str] = None
@dataclass(frozen=True)
class GrokRuntimeContract:
agent_id: str
guard_path: str
audit_path: str
def _validate_handler(
value: Any,
event: str,
group_index: int,
handler_index: int,
) -> JsonObject:
label = (
f"Grok user hooks 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 handler_type not in ("command", "http"):
raise ValueError(f'{label} has unsupported type "{handler_type}"')
if handler_type == "command" and (
not isinstance(handler.get("command"), str) or not handler["command"]
):
raise ValueError(f"{label} requires a non-empty command")
if handler_type == "http" and (
not isinstance(handler.get("url"), str) or not handler["url"]
):
raise ValueError(f"{label} requires a non-empty url")
timeout = handler.get("timeout")
if timeout is not None and (type(timeout) is not int or timeout < 0):
raise ValueError(f"{label} timeout must be a non-negative integer")
environment = handler.get("env")
if environment is not None and (
not isinstance(environment, dict)
or any(not isinstance(item, str) for item in environment.values())
):
raise ValueError(f"{label} env must map names to strings")
return handler
def _validate_group(value: Any, event: str, group_index: int) -> JsonObject:
label = f"Grok user hooks group hooks.{event}[{group_index}]"
if not isinstance(value, dict):
raise ValueError(f"{label} must be an object")
group = dict(value)
matcher = group.get("matcher")
if "matcher" in group and not isinstance(matcher, str):
raise ValueError(f"{label} matcher must be a string")
if "matcher" in group and event in MATCHER_REJECTING_EVENTS:
raise ValueError(f"{label} cannot declare a matcher for {event}")
handlers = group.get("hooks")
if not isinstance(handlers, list):
raise ValueError(f"{label} must contain a hooks array")
group["hooks"] = [
_validate_handler(handler, event, group_index, handler_index)
for handler_index, handler in enumerate(handlers)
]
return group
def _read_hooks(root: JsonObject) -> GrokHooks:
if "hooks" not in root:
return {}
value = root["hooks"]
if not isinstance(value, dict):
raise ValueError('Grok user hooks field "hooks" must be an object')
hooks: GrokHooks = {}
for event, groups in value.items():
if not isinstance(groups, list):
raise ValueError(
f'Grok user hooks field "hooks.{event}" must be an array'
)
hooks[event] = [
_validate_group(group, event, index)
for index, group in enumerate(groups)
]
return hooks
def parse_grok_document(config_path: str, raw: str) -> GrokDocument:
root = parse_json_object(raw, f"Grok user hooks at {config_path}")
return GrokDocument(True, config_path, root, _read_hooks(root), raw)
def create_grok_document(config_path: str) -> GrokDocument:
return GrokDocument(False, config_path, {}, {})
def build_grok_group(script_path: str) -> JsonObject:
return {
"hooks": [{
"type": "command",
"command": build_grok_command(script_path),
"timeout": HOOK_TIMEOUT_SECONDS,
}]
}
def _exact_managed_group(group: JsonObject) -> bool:
return set(group) == {"hooks"}
def _managed_reference(
handler: JsonObject, script_name: str
) -> Optional[GrokRuntimeReference]:
if (
set(handler) != {"type", "command", "timeout"}
or handler.get("type") != "command"
or type(handler.get("timeout")) is not int
or handler.get("timeout") != HOOK_TIMEOUT_SECONDS
or not isinstance(handler.get("command"), str)
):
return None
return grok_runtime_reference(str(handler["command"]), script_name)
def _managed_contract(event: str) -> Optional[Tuple[str, str]]:
if event == "PreToolUse":
return event, GUARD_SCRIPT
if event in ("PostToolUse", "PostToolUseFailure"):
return event, AUDIT_SCRIPT
return None
def _remove_from_groups(
groups: List[JsonObject], script_name: str, agent_id: str
) -> List[JsonObject]:
result: List[JsonObject] = []
for group in groups:
if not _exact_managed_group(group):
result.append(group)
continue
kept = []
for handler in group["hooks"]:
reference = _managed_reference(handler, script_name)
remove = reference is not None and (
not agent_id or same_grok_agent_id(reference.agent_id, agent_id)
)
if not remove:
kept.append(handler)
if kept:
result.append({"hooks": kept})
return result
def remove_managed_grok_hooks(
hooks: GrokHooks, agent_id: str = ""
) -> GrokHooks:
result = {event: list(groups) for event, groups in hooks.items()}
for event, script_name in (
("PreToolUse", GUARD_SCRIPT),
("PostToolUse", AUDIT_SCRIPT),
("PostToolUseFailure", AUDIT_SCRIPT),
):
groups = _remove_from_groups(
result.get(event, []), script_name, agent_id
)
if groups:
result[event] = groups
else:
result.pop(event, None)
return result
def _entirely_managed(document: GrokDocument) -> bool:
if not document.exists or set(document.root) != {"hooks"}:
return False
if not document.hooks:
return False
count = 0
for event, groups in document.hooks.items():
contract = _managed_contract(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[1]) is None
for handler in group["hooks"]
)
):
return False
count += len(group["hooks"])
return count > 0
def render_grok_document(
document: GrokDocument, hooks: GrokHooks
) -> RenderedGrokDocument:
if not document.exists and not hooks:
return RenderedGrokDocument(document, False)
if not hooks and _entirely_managed(document):
return RenderedGrokDocument(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_grok_document(document.config_path, next_source)
return RenderedGrokDocument(
document,
next_source != document.raw,
next_source,
)
def _references_for_event(
groups: List[JsonObject], script_name: str
) -> Dict[str, List[GrokRuntimeReference]]:
result: Dict[str, List[GrokRuntimeReference]] = {}
for group in groups:
if not _exact_managed_group(group):
continue
for handler in group["hooks"]:
reference = _managed_reference(handler, script_name)
if reference is not None:
result.setdefault(
os.path.normcase(reference.agent_id), []
).append(reference)
return result
def grok_runtime_contracts(hooks: GrokHooks) -> List[GrokRuntimeContract]:
guards = _references_for_event(hooks.get("PreToolUse", []), GUARD_SCRIPT)
successes = _references_for_event(
hooks.get("PostToolUse", []), AUDIT_SCRIPT
)
failures = _references_for_event(
hooks.get("PostToolUseFailure", []), AUDIT_SCRIPT
)
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_grok_path(success[0].script_path, failure[0].script_path):
continue
contracts.append(GrokRuntimeContract(
agent_id=guard[0].agent_id,
guard_path=guard[0].script_path,
audit_path=success[0].script_path,
))
return contracts
+178
View File
@@ -0,0 +1,178 @@
"""Transactional Grok 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, source_change, write_changes
from .base import InstallConfig
from .grok_command import runtime_root, same_grok_path
from .grok_contract import (
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
GrokDocument,
RenderedGrokDocument,
)
from .grok_io import (
validate_api_origin,
validate_private_key,
validate_runtime_tree,
)
from .hook_template import generate_guard_script, generate_hook_script
@dataclass(frozen=True)
class GrokRuntimePaths:
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) -> GrokRuntimePaths:
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_grok_path(config.get("guard_script_path", ""), guard_path):
raise ValueError(
"Elydora guard runtime must use the managed agent directory: "
f"{guard_path}"
)
return GrokRuntimePaths(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"Grok 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_grok_installation(
config: InstallConfig, document: GrokDocument
) -> GrokRuntimePaths:
if not document.config_path:
raise ValueError("Grok installation requires a hook configuration 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 rendered_change(
rendered: RenderedGrokDocument,
) -> Optional[FileChange]:
if not rendered.changed:
return None
return source_change(
rendered.document.config_path,
"Grok user hooks",
rendered.document.raw,
rendered.next_source,
0o600,
MAX_SOURCE_BYTES,
)
def _present(changes: List[Optional[FileChange]]) -> List[FileChange]:
return [change for change in changes if change is not None]
def prepare_grok_installation(
config: InstallConfig,
paths: GrokRuntimePaths,
rendered: RenderedGrokDocument,
) -> List[FileChange]:
guard_script = generate_guard_script(
AGENT_KEY, paths.agent_id, deny_protocol="grok"
)
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_grok_installation(changes: List[FileChange]) -> None:
write_changes(changes, "Install Grok hooks")
def prepare_grok_uninstall(rendered: RenderedGrokDocument) -> List[FileChange]:
return _present([rendered_change(rendered)])
def commit_grok_uninstall(changes: List[FileChange]) -> None:
write_changes(changes, "Uninstall Grok hooks")
+218
View File
@@ -0,0 +1,218 @@
"""Grok user-hook 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,
physical_directory_exists,
physical_file_exists,
read_physical_file,
)
from ._strict_json import JsonObject, parse_json_object
from .grok_command import runtime_root, same_grok_agent_id, same_grok_path
from .grok_contract import (
AGENT_KEY,
GrokDocument,
GrokRuntimeContract,
create_grok_document,
parse_grok_document,
)
CONFIG_FILE = "elydora-audit.json"
def grok_config_path() -> str:
configured = os.environ.get("GROK_HOME")
grok_home = (
os.path.join(os.path.expanduser("~"), ".grok")
if configured is None or configured == ""
else os.path.abspath(configured)
)
return os.path.join(grok_home, "hooks", CONFIG_FILE)
def read_grok_document() -> GrokDocument:
config_path = grok_config_path()
hooks_directory = os.path.dirname(config_path)
physical_directory_exists(
os.path.dirname(hooks_directory), "Grok home directory"
)
physical_directory_exists(hooks_directory, "Grok hooks directory")
snapshot = read_physical_file(config_path, "Grok user hooks")
if snapshot is None:
return create_grok_document(config_path)
return parse_grok_document(config_path, snapshot.contents)
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_grok_agent_id(agent_id, expected_agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
f"Elydora runtime identity does not match Grok hooks: {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_grok_agent_id(configured_id, agent_id)
or config.get("agent_name") != AGENT_KEY
):
raise ValueError(
f"Elydora runtime config identity does not match Grok agent {agent_id}: "
f"{config_path}"
)
def _runtime_contract_exists(contract: GrokRuntimeContract) -> bool:
root = runtime_root()
agent_directory = os.path.dirname(contract.guard_path)
if (
not same_grok_path(os.path.dirname(agent_directory), root)
or not same_grok_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 grok_runtime_files_exist(contracts: List[GrokRuntimeContract]) -> bool:
return any(_runtime_contract_exists(contract) for contract in contracts)
+9 -1
View File
@@ -13,6 +13,7 @@ def generate_guard_script(
success_output: str = "",
*,
fail_closed: bool = False,
deny_protocol: str = "",
) -> str:
"""Return a self-contained status guard for a command-hook provider."""
return f'''#!{sys.executable}
@@ -32,6 +33,7 @@ AGENT_NAME = {agent_name!r}
AGENT_ID = {agent_id!r}
SUCCESS_OUTPUT = {success_output!r}
FAIL_CLOSED = {fail_closed!r}
DENY_PROTOCOL = {deny_protocol!r}
ELYDORA_DIR = os.path.join(os.path.expanduser("~"), ".elydora")
CONFIG_PATH = os.path.join(ELYDORA_DIR, AGENT_ID, "config.json")
STATUS_CACHE_PATH = os.path.join(ELYDORA_DIR, AGENT_ID, "status-cache.json")
@@ -49,13 +51,19 @@ def validate_status(value, source):
def block_agent(status):
state = "frozen" if status == "frozen" else "revoked"
message = 'Agent "' + AGENT_NAME + '" is ' + state + " in Elydora."
if SUCCESS_OUTPUT:
if DENY_PROTOCOL == "cursor":
sys.stdout.write(json.dumps({{
"permission": "deny",
"userMessage": message,
"agentMessage": message + " Tool execution is blocked.",
}}) + "\\n")
sys.stdout.flush()
elif DENY_PROTOCOL == "grok":
sys.stdout.write(json.dumps({{
"decision": "deny",
"reason": message,
}}) + "\\n")
sys.stdout.flush()
sys.stderr.write("[Elydora guard] " + message + " Tool execution blocked.\\n")
raise SystemExit(2)
+1 -1
View File
@@ -48,7 +48,7 @@ SUPPORTED_AGENTS: Dict[str, Dict[str, str]] = {
},
"grok": {
"name": "Grok Build",
"hook_event": "PreToolUse/PostToolUse",
"hook_event": "PreToolUse/PostToolUse/PostToolUseFailure",
"config_path": "~/.grok/hooks/elydora-audit.json",
},
"kirocli": {