fix(cline): mirror transactional Python adapter
This commit is contained in:
1 parent
4ad139c60a
commit
052116081a
10 files changed
+1375
-572
No files matched your search
@@ -2,107 +2,69 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Tuple
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .cline_contract import (
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
HookFile,
|
||||
build_metadata,
|
||||
build_wrapper,
|
||||
elydora_dir,
|
||||
HookPaths,
|
||||
resolve_hook_files,
|
||||
runtime_contract,
|
||||
)
|
||||
from .cline_io import (
|
||||
PendingWrite,
|
||||
read_hook_file,
|
||||
remove_owned_hooks,
|
||||
require_available_hook_file,
|
||||
require_runtime,
|
||||
runtime_files_exist,
|
||||
write_hook_pair,
|
||||
from .cline_installation import (
|
||||
commit_cline_installation,
|
||||
commit_cline_uninstall,
|
||||
preflight_cline_installation,
|
||||
prepare_cline_installation,
|
||||
prepare_cline_uninstall,
|
||||
)
|
||||
from .hook_template import generate_hook_script
|
||||
from .cline_io import (
|
||||
read_hook_file,
|
||||
require_available_hook_file,
|
||||
runtime_files_exist,
|
||||
)
|
||||
|
||||
|
||||
def _read_hook_pair() -> Tuple[HookPaths, HookFile, HookFile]:
|
||||
paths = resolve_hook_files()
|
||||
return (
|
||||
paths,
|
||||
read_hook_file(paths.guard_path),
|
||||
read_hook_file(paths.audit_path),
|
||||
)
|
||||
|
||||
|
||||
def _require_available_pair(guard_file: HookFile, audit_file: HookFile) -> None:
|
||||
require_available_hook_file(guard_file)
|
||||
require_available_hook_file(audit_file)
|
||||
|
||||
|
||||
class ClinePlugin(AgentPlugin):
|
||||
"""Install Elydora into Cline's global file-hook directory."""
|
||||
|
||||
manages_guard_runtime = True
|
||||
|
||||
def preflight_install(self, config: InstallConfig) -> None:
|
||||
_paths, guard_file, audit_file = _read_hook_pair()
|
||||
_require_available_pair(guard_file, audit_file)
|
||||
preflight_cline_installation(config, guard_file, audit_file)
|
||||
|
||||
def install(self, config: InstallConfig) -> None:
|
||||
agent_id = config.get("agent_id", "")
|
||||
if not agent_id:
|
||||
raise ValueError("agent_id is required")
|
||||
paths = resolve_hook_files()
|
||||
guard_state = read_hook_file(paths.guard_path)
|
||||
audit_state = read_hook_file(paths.audit_path)
|
||||
require_available_hook_file(guard_state)
|
||||
require_available_hook_file(audit_state)
|
||||
|
||||
guard_path = config.get("guard_script_path", "")
|
||||
require_runtime(guard_path, "Elydora guard runtime")
|
||||
agent_directory = os.path.join(elydora_dir(), agent_id)
|
||||
audit_path = os.path.join(agent_directory, AUDIT_SCRIPT)
|
||||
guard_metadata = build_metadata("guard", agent_id, guard_path)
|
||||
audit_metadata = build_metadata("audit", agent_id, audit_path)
|
||||
guard_source = build_wrapper(guard_metadata)
|
||||
audit_source = build_wrapper(audit_metadata)
|
||||
runtime_contract(
|
||||
HookFile(True, paths.guard_path, guard_source, guard_metadata),
|
||||
HookFile(True, paths.audit_path, audit_source, audit_metadata),
|
||||
)
|
||||
|
||||
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"),
|
||||
)
|
||||
write_json_atomic(
|
||||
os.path.join(agent_directory, "config.json"),
|
||||
runtime_config,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
)
|
||||
write_text_atomic(
|
||||
os.path.join(agent_directory, "private.key"),
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
write_text_atomic(
|
||||
audit_path,
|
||||
audit_script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
write_hook_pair(
|
||||
PendingWrite(guard_state, guard_source),
|
||||
PendingWrite(audit_state, audit_source),
|
||||
)
|
||||
_paths, guard_file, audit_file = _read_hook_pair()
|
||||
_require_available_pair(guard_file, audit_file)
|
||||
changes = prepare_cline_installation(config, guard_file, audit_file)
|
||||
commit_cline_installation(changes)
|
||||
print("Cline: user-level PreToolUse and PostToolUse hooks installed.")
|
||||
|
||||
def uninstall(self, agent_id: str = "") -> None:
|
||||
paths = resolve_hook_files()
|
||||
guard_state = read_hook_file(paths.guard_path)
|
||||
audit_state = read_hook_file(paths.audit_path)
|
||||
remove_owned_hooks((guard_state, audit_state), agent_id)
|
||||
_paths, guard_file, audit_file = _read_hook_pair()
|
||||
changes = prepare_cline_uninstall((guard_file, audit_file), agent_id)
|
||||
commit_cline_uninstall(changes)
|
||||
|
||||
def status(self) -> PluginStatus:
|
||||
paths = resolve_hook_files()
|
||||
guard_state = read_hook_file(paths.guard_path)
|
||||
audit_state = read_hook_file(paths.audit_path)
|
||||
contract = runtime_contract(guard_state, audit_state)
|
||||
paths, guard_file, audit_file = _read_hook_pair()
|
||||
contract = runtime_contract(guard_file, audit_file)
|
||||
if contract is None:
|
||||
return PluginStatus(
|
||||
installed=False,
|
||||
@@ -115,7 +77,7 @@ class ClinePlugin(AgentPlugin):
|
||||
if installed
|
||||
else (
|
||||
f"Configured at {paths.hooks_directory}; "
|
||||
"runtime scripts missing"
|
||||
"managed runtime incomplete"
|
||||
)
|
||||
)
|
||||
return PluginStatus(
|
||||
|
||||
@@ -8,6 +8,8 @@ import json
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from elydora._runtime_paths import resolve_agent_directory
|
||||
|
||||
|
||||
AGENT_KEY = "cline"
|
||||
GUARD_FILE_NAME = "PreToolUse.mjs"
|
||||
@@ -177,7 +179,7 @@ async function main() {
|
||||
|
||||
if (hookKind === 'guard' && result.code === 2) {
|
||||
const errorMessage = result.stderr.trim() || 'Agent is frozen by Elydora.';
|
||||
process.stdout.write('HOOK_CONTROL\\t' + JSON.stringify({ cancel: true, errorMessage }) + '\\n');
|
||||
process.stdout.write(JSON.stringify({ cancel: true, errorMessage }) + '\\n');
|
||||
return;
|
||||
}
|
||||
if (result.signal) throw new Error('runtime terminated by signal ' + result.signal);
|
||||
@@ -251,11 +253,6 @@ def assert_wrapper_integrity(file: HookFile) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _validate_agent_segment(agent_id: str) -> None:
|
||||
if agent_id in {".", ".."} or os.path.basename(agent_id) != agent_id:
|
||||
raise ValueError("Elydora Cline hook metadata contains an invalid agentId")
|
||||
|
||||
|
||||
def runtime_contract(
|
||||
guard_file: HookFile,
|
||||
audit_file: HookFile,
|
||||
@@ -270,8 +267,7 @@ def runtime_contract(
|
||||
raise ValueError("Elydora Cline hook files contain mismatched event metadata")
|
||||
if not same_agent_id(guard.agent_id, audit.agent_id):
|
||||
raise ValueError("Elydora Cline hook files reference different agents")
|
||||
_validate_agent_segment(guard.agent_id)
|
||||
agent_directory = os.path.join(elydora_dir(), guard.agent_id)
|
||||
agent_directory = resolve_agent_directory(elydora_dir(), guard.agent_id)
|
||||
expected_guard = os.path.join(agent_directory, GUARD_SCRIPT)
|
||||
expected_audit = os.path.join(agent_directory, AUDIT_SCRIPT)
|
||||
if not _same_path(guard.runtime_path, expected_guard) or not _same_path(
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Transactional Cline hook and runtime installation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
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, file_change, source_change, write_changes
|
||||
from .base import InstallConfig
|
||||
from .cline_contract import (
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
HookFile,
|
||||
assert_wrapper_integrity,
|
||||
build_metadata,
|
||||
build_wrapper,
|
||||
elydora_dir,
|
||||
resolve_hook_files,
|
||||
runtime_contract,
|
||||
same_agent_id,
|
||||
)
|
||||
from .cline_io import (
|
||||
validate_api_origin,
|
||||
validate_hook_tree,
|
||||
validate_private_key,
|
||||
validate_runtime_tree,
|
||||
)
|
||||
from .guard_template import generate_guard_script
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClineRuntimePaths:
|
||||
agent_id: str
|
||||
agent_directory: str
|
||||
guard_path: str
|
||||
audit_path: str
|
||||
|
||||
|
||||
def _same_path(left: str, right: str) -> bool:
|
||||
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
|
||||
os.path.abspath(right)
|
||||
)
|
||||
|
||||
|
||||
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) -> ClineRuntimePaths:
|
||||
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_path(config.get("guard_script_path", ""), guard_path):
|
||||
raise ValueError(
|
||||
f"Elydora guard runtime must use the managed agent directory: {guard_path}"
|
||||
)
|
||||
return ClineRuntimePaths(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"Cline 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")
|
||||
if not os.path.isabs(sys.executable):
|
||||
raise RuntimeError("Cline requires an absolute Python executable path")
|
||||
_agent_paths(config)
|
||||
|
||||
|
||||
def _validate_hook_files(guard_file: HookFile, audit_file: HookFile) -> None:
|
||||
expected = resolve_hook_files()
|
||||
if not _same_path(guard_file.file_path, expected.guard_path) or not _same_path(
|
||||
audit_file.file_path, expected.audit_path
|
||||
):
|
||||
raise ValueError("Cline installation received unexpected hook paths")
|
||||
validate_hook_tree(expected.hooks_directory)
|
||||
|
||||
|
||||
def preflight_cline_installation(
|
||||
config: InstallConfig,
|
||||
guard_file: HookFile,
|
||||
audit_file: HookFile,
|
||||
) -> ClineRuntimePaths:
|
||||
_validate_install_config(config)
|
||||
_validate_hook_files(guard_file, audit_file)
|
||||
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 _hook_change(
|
||||
file: HookFile, label: str, next_source: Optional[str]
|
||||
) -> Optional[FileChange]:
|
||||
original = file.source if file.exists else None
|
||||
if file.exists and original is None:
|
||||
raise RuntimeError(f"{label} snapshot is missing source")
|
||||
return source_change(
|
||||
file.file_path,
|
||||
label,
|
||||
original,
|
||||
next_source,
|
||||
0o700,
|
||||
)
|
||||
|
||||
|
||||
def _present(changes: Sequence[Optional[FileChange]]) -> List[FileChange]:
|
||||
return [change for change in changes if change is not None]
|
||||
|
||||
|
||||
def prepare_cline_installation(
|
||||
config: InstallConfig,
|
||||
guard_file: HookFile,
|
||||
audit_file: HookFile,
|
||||
) -> List[FileChange]:
|
||||
paths = preflight_cline_installation(config, guard_file, audit_file)
|
||||
guard_metadata = build_metadata("guard", paths.agent_id, paths.guard_path)
|
||||
audit_metadata = build_metadata("audit", paths.agent_id, paths.audit_path)
|
||||
guard_wrapper = build_wrapper(guard_metadata)
|
||||
audit_wrapper = build_wrapper(audit_metadata)
|
||||
runtime_contract(
|
||||
HookFile(True, guard_file.file_path, guard_wrapper, guard_metadata),
|
||||
HookFile(True, audit_file.file_path, audit_wrapper, audit_metadata),
|
||||
)
|
||||
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,
|
||||
)
|
||||
changes = _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
|
||||
),
|
||||
_hook_change(guard_file, "Cline PreToolUse hook", guard_wrapper),
|
||||
_hook_change(audit_file, "Cline PostToolUse hook", audit_wrapper),
|
||||
)
|
||||
)
|
||||
validate_runtime_tree(paths.agent_directory, paths.agent_id)
|
||||
validate_hook_tree(os.path.dirname(guard_file.file_path))
|
||||
return changes
|
||||
|
||||
|
||||
def commit_cline_installation(changes: Sequence[FileChange]) -> None:
|
||||
write_changes(changes, "Install Cline hooks")
|
||||
|
||||
|
||||
def prepare_cline_uninstall(
|
||||
files: Sequence[HookFile], agent_id: str = ""
|
||||
) -> List[FileChange]:
|
||||
owned = [
|
||||
file
|
||||
for file in files
|
||||
if file.metadata is not None
|
||||
and (not agent_id or same_agent_id(file.metadata.agent_id, agent_id))
|
||||
]
|
||||
changes: List[Optional[FileChange]] = []
|
||||
for file in owned:
|
||||
metadata = file.metadata
|
||||
assert metadata is not None
|
||||
assert_wrapper_integrity(file)
|
||||
changes.append(
|
||||
_hook_change(file, f"Cline {metadata.kind} hook", None)
|
||||
)
|
||||
return _present(changes)
|
||||
|
||||
|
||||
def commit_cline_uninstall(changes: Sequence[FileChange]) -> None:
|
||||
write_changes(changes, "Uninstall Cline hooks")
|
||||
@@ -1,53 +1,57 @@
|
||||
"""Fail-fast Cline hook I/O and runtime validation."""
|
||||
"""Physical Cline hook and managed runtime validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import base64
|
||||
import os
|
||||
import tempfile
|
||||
from typing import List, Sequence, Tuple
|
||||
from typing import Any, Optional
|
||||
import urllib.parse
|
||||
|
||||
from ._file_io import (
|
||||
read_json,
|
||||
regular_file_exists,
|
||||
remove_file,
|
||||
require_runtime,
|
||||
write_text_atomic,
|
||||
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 .cline_contract import (
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
HookFile,
|
||||
RuntimeContract,
|
||||
elydora_dir,
|
||||
parse_metadata,
|
||||
same_agent_id,
|
||||
)
|
||||
from .guard_template import generate_guard_script
|
||||
from .hook_template import generate_hook_script
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingWrite:
|
||||
state: HookFile
|
||||
source: str
|
||||
def _same_path(left: str, right: str) -> bool:
|
||||
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
|
||||
os.path.abspath(right)
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StagedFile:
|
||||
state: HookFile
|
||||
temporary_path: str
|
||||
def validate_hook_tree(hooks_directory: str) -> None:
|
||||
physical_directory_exists(
|
||||
os.path.dirname(hooks_directory), "Cline configuration directory"
|
||||
)
|
||||
physical_directory_exists(hooks_directory, "Cline hooks directory")
|
||||
|
||||
|
||||
def read_hook_file(file_path: str) -> HookFile:
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8") as file:
|
||||
source = file.read()
|
||||
except FileNotFoundError:
|
||||
validate_hook_tree(os.path.dirname(file_path))
|
||||
snapshot = read_physical_file(file_path, "Cline hook")
|
||||
if snapshot is None:
|
||||
return HookFile(False, file_path)
|
||||
except OSError as error:
|
||||
raise OSError(f"Read Cline hook at {file_path}: {error}") from error
|
||||
return HookFile(
|
||||
exists=True,
|
||||
file_path=file_path,
|
||||
source=source,
|
||||
metadata=parse_metadata(file_path, source),
|
||||
source=snapshot.contents,
|
||||
metadata=parse_metadata(file_path, snapshot.contents),
|
||||
)
|
||||
|
||||
|
||||
@@ -59,136 +63,194 @@ def require_available_hook_file(file: HookFile) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _remove_temporary(path: str) -> None:
|
||||
def validate_api_origin(value: str, label: str = "base_url") -> None:
|
||||
try:
|
||||
os.remove(path)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
|
||||
|
||||
def _stage_file(write: PendingWrite) -> StagedFile:
|
||||
directory = os.path.dirname(write.state.file_path)
|
||||
try:
|
||||
os.makedirs(directory, mode=0o700, exist_ok=True)
|
||||
except OSError as error:
|
||||
raise OSError(f"Create Cline hooks directory at {directory}: {error}") from error
|
||||
descriptor = -1
|
||||
temporary_path = ""
|
||||
try:
|
||||
descriptor, temporary_path = tempfile.mkstemp(
|
||||
prefix=f".{os.path.basename(write.state.file_path)}.",
|
||||
suffix=".tmp",
|
||||
dir=directory,
|
||||
text=True,
|
||||
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"
|
||||
)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8", newline="") as file:
|
||||
descriptor = -1
|
||||
file.write(write.source)
|
||||
file.flush()
|
||||
os.fsync(file.fileno())
|
||||
os.chmod(temporary_path, 0o700)
|
||||
return StagedFile(write.state, temporary_path)
|
||||
except Exception as error:
|
||||
if descriptor >= 0:
|
||||
try:
|
||||
os.close(descriptor)
|
||||
except OSError as close_error:
|
||||
_remove_temporary(temporary_path)
|
||||
raise OSError(
|
||||
f"Stage Cline hook at {write.state.file_path}: {error}; "
|
||||
f"close failed: {close_error}"
|
||||
) from error
|
||||
_remove_temporary(temporary_path)
|
||||
raise OSError(
|
||||
f"Stage Cline hook at {write.state.file_path}: {error}"
|
||||
|
||||
|
||||
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 _rollback_file(state: HookFile) -> None:
|
||||
if state.exists:
|
||||
if state.source is None:
|
||||
raise RuntimeError("Existing Cline hook rollback state is missing source")
|
||||
write_text_atomic(
|
||||
state.file_path,
|
||||
state.source,
|
||||
0o700,
|
||||
"Cline hook rollback",
|
||||
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}'
|
||||
)
|
||||
else:
|
||||
remove_file(state.file_path, "Cline hook rollback")
|
||||
_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_agent_id(agent_id, expected_agent_id)
|
||||
or config.get("agent_name") != AGENT_KEY
|
||||
):
|
||||
raise ValueError(
|
||||
f"Elydora runtime identity does not match Cline 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 write_hook_pair(guard: PendingWrite, audit: PendingWrite) -> None:
|
||||
staged: List[StagedFile] = []
|
||||
try:
|
||||
staged.append(_stage_file(guard))
|
||||
staged.append(_stage_file(audit))
|
||||
except Exception as error:
|
||||
cleanup_errors: List[str] = []
|
||||
for item in staged:
|
||||
try:
|
||||
_remove_temporary(item.temporary_path)
|
||||
except OSError as cleanup_error:
|
||||
cleanup_errors.append(str(cleanup_error))
|
||||
suffix = f"; cleanup failed: {'; '.join(cleanup_errors)}" if cleanup_errors else ""
|
||||
raise OSError(f"Stage Cline hook pair: {error}{suffix}") from error
|
||||
|
||||
committed: List[StagedFile] = []
|
||||
try:
|
||||
for item in staged:
|
||||
os.replace(item.temporary_path, item.state.file_path)
|
||||
committed.append(item)
|
||||
except Exception as error:
|
||||
recovery_errors: List[str] = []
|
||||
for item in reversed(committed):
|
||||
try:
|
||||
_rollback_file(item.state)
|
||||
except (OSError, RuntimeError) as rollback_error:
|
||||
recovery_errors.append(str(rollback_error))
|
||||
for item in staged[len(committed):]:
|
||||
try:
|
||||
_remove_temporary(item.temporary_path)
|
||||
except OSError as cleanup_error:
|
||||
recovery_errors.append(str(cleanup_error))
|
||||
suffix = f"; recovery failed: {'; '.join(recovery_errors)}" if recovery_errors else ""
|
||||
raise OSError(f"Write Cline hook pair: {error}{suffix}") from error
|
||||
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 remove_owned_hooks(files: Sequence[HookFile], agent_id: str = "") -> None:
|
||||
for file in files:
|
||||
owned_agent_id = file.metadata.agent_id if file.metadata else ""
|
||||
if not owned_agent_id or (
|
||||
agent_id and not same_agent_id(owned_agent_id, agent_id)
|
||||
):
|
||||
continue
|
||||
remove_file(file.file_path, "Cline hook")
|
||||
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_SCRIPT, "Elydora guard runtime"),
|
||||
(AUDIT_SCRIPT, "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_agent_id(configured_id, agent_id)
|
||||
or config.get("agent_name") != AGENT_KEY
|
||||
):
|
||||
raise ValueError(
|
||||
"Elydora runtime config identity does not match Cline agent "
|
||||
f"{agent_id}: {config_path}"
|
||||
)
|
||||
|
||||
|
||||
def _valid_contract_paths(contract: RuntimeContract) -> bool:
|
||||
return (
|
||||
_same_path(os.path.dirname(contract.agent_directory), elydora_dir())
|
||||
and _same_path(
|
||||
contract.guard_path,
|
||||
os.path.join(contract.agent_directory, GUARD_SCRIPT),
|
||||
)
|
||||
and _same_path(
|
||||
contract.audit_path,
|
||||
os.path.join(contract.agent_directory, AUDIT_SCRIPT),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def runtime_files_exist(contract: RuntimeContract) -> bool:
|
||||
config_path = os.path.join(contract.agent_directory, "config.json")
|
||||
config = read_json(config_path, "Elydora runtime config")
|
||||
if config is None:
|
||||
if not _valid_contract_paths(contract):
|
||||
return False
|
||||
config_agent_id = config.get("agent_id")
|
||||
if (
|
||||
config.get("agent_name") != AGENT_KEY
|
||||
or not isinstance(config_agent_id, str)
|
||||
or not same_agent_id(config_agent_id, contract.agent_id)
|
||||
root = elydora_dir()
|
||||
if not physical_directory_exists(root, "Elydora runtime directory"):
|
||||
return False
|
||||
if not physical_directory_exists(
|
||||
contract.agent_directory, "Elydora agent runtime directory"
|
||||
):
|
||||
return False
|
||||
files: Tuple[Tuple[str, str], ...] = (
|
||||
(contract.guard_path, "Elydora guard runtime"),
|
||||
(contract.audit_path, "Elydora audit runtime"),
|
||||
config_path = os.path.join(contract.agent_directory, "config.json")
|
||||
key_path = os.path.join(contract.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 any(item is None for item in (config, key, guard, audit)):
|
||||
return False
|
||||
assert config is not None
|
||||
assert key is not None
|
||||
assert guard is not None
|
||||
assert audit is not None
|
||||
_validate_runtime_config(config, contract.agent_id, config_path)
|
||||
validate_private_key(key.contents, "Elydora private key")
|
||||
expected_audit = generate_hook_script(
|
||||
org_id="",
|
||||
agent_id=contract.agent_id,
|
||||
kid="",
|
||||
base_url="",
|
||||
native_payload=True,
|
||||
agent_name=AGENT_KEY,
|
||||
)
|
||||
return (
|
||||
guard.contents == generate_guard_script(AGENT_KEY, contract.agent_id)
|
||||
and audit.contents == expected_audit
|
||||
)
|
||||
return all(regular_file_exists(path, label) for path, label in files)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PendingWrite",
|
||||
"read_hook_file",
|
||||
"remove_owned_hooks",
|
||||
"require_available_hook_file",
|
||||
"require_runtime",
|
||||
"runtime_files_exist",
|
||||
"write_hook_pair",
|
||||
"validate_api_origin",
|
||||
"validate_hook_tree",
|
||||
"validate_private_key",
|
||||
"validate_runtime_tree",
|
||||
]
|
||||
Reference in new issue
Block a user