feat: add native Cline hook integration

This commit is contained in:
ZacharyZhang-NY committed 2026-07-19 09:56:50 -04:00
1 parent 86152c8179
commit e839c77a4b
9 files changed
+1119 -3

No files matched your search

+126
View File
@@ -0,0 +1,126 @@
"""Cline native user-level file-hook integration."""
from __future__ import annotations
import os
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,
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 .hook_template import generate_hook_script
class ClinePlugin(AgentPlugin):
"""Install Elydora into Cline's global file-hook directory."""
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,
private_key=config.get("private_key", ""),
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),
)
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)
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)
if contract is None:
return PluginStatus(
installed=False,
agent=AGENT_KEY,
details="Not installed",
)
installed = runtime_files_exist(contract)
details = (
f"Config: {paths.hooks_directory}"
if installed
else (
f"Configured at {paths.hooks_directory}; "
"runtime scripts missing"
)
)
return PluginStatus(
installed=installed,
agent=AGENT_KEY,
details=details,
)
+288
View File
@@ -0,0 +1,288 @@
"""Cline file-hook contract and exact Elydora ownership metadata."""
from __future__ import annotations
import base64
from dataclasses import dataclass
import json
import os
from typing import Any, Dict, Optional
AGENT_KEY = "cline"
GUARD_FILE_NAME = "PreToolUse.mjs"
AUDIT_FILE_NAME = "PostToolUse.mjs"
GUARD_SCRIPT = "guard.py"
AUDIT_SCRIPT = "hook.py"
_METADATA_MARKER = "// @elydora-cline-hook "
_METADATA_VERSION = 1
JsonObject = Dict[str, Any]
@dataclass(frozen=True)
class HookMetadata:
version: int
kind: str
agent_id: str
runtime_path: str
@dataclass(frozen=True)
class HookFile:
exists: bool
file_path: str
source: Optional[str] = None
metadata: Optional[HookMetadata] = None
@dataclass(frozen=True)
class HookPaths:
hooks_directory: str
guard_path: str
audit_path: str
@dataclass(frozen=True)
class RuntimeContract:
agent_id: str
agent_directory: str
guard_path: str
audit_path: str
def home_dir() -> str:
return os.path.expanduser("~")
def elydora_dir() -> str:
return os.path.join(home_dir(), ".elydora")
def same_agent_id(left: str, right: str) -> bool:
return os.path.normcase(left) == os.path.normcase(right)
def _same_path(left: str, right: str) -> bool:
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
os.path.abspath(right)
)
def resolve_hooks_directory() -> str:
configured = os.environ.get("CLINE_DIR", "").strip()
cline_directory = (
os.path.abspath(configured)
if configured
else os.path.join(home_dir(), ".cline")
)
return os.path.join(cline_directory, "hooks")
def resolve_hook_files() -> HookPaths:
hooks_directory = resolve_hooks_directory()
return HookPaths(
hooks_directory=hooks_directory,
guard_path=os.path.join(hooks_directory, GUARD_FILE_NAME),
audit_path=os.path.join(hooks_directory, AUDIT_FILE_NAME),
)
def build_metadata(kind: str, agent_id: str, runtime_path: str) -> HookMetadata:
if kind not in {"guard", "audit"}:
raise ValueError('Cline hook kind must be "guard" or "audit"')
if not agent_id:
raise ValueError("agent_id is required")
if not os.path.isabs(runtime_path):
raise ValueError(f"Cline {kind} runtime path must be absolute")
return HookMetadata(_METADATA_VERSION, kind, agent_id, runtime_path)
def _metadata_object(metadata: HookMetadata) -> JsonObject:
return {
"version": metadata.version,
"kind": metadata.kind,
"agentId": metadata.agent_id,
"runtimePath": metadata.runtime_path,
}
def _encode_metadata(metadata: HookMetadata) -> str:
raw = json.dumps(_metadata_object(metadata), separators=(",", ":"))
return base64.urlsafe_b64encode(raw.encode("utf-8")).rstrip(b"=").decode("ascii")
def build_wrapper(metadata: HookMetadata) -> str:
template = """#!/usr/bin/env node
__METADATA_MARKER____METADATA__
import { spawn } from 'node:child_process';
import { readFileSync, statSync } from 'node:fs';
import { isAbsolute } from 'node:path';
const hookKind = __HOOK_KIND__;
const runtimePath = __RUNTIME_PATH__;
function resolveRuntimeExecutable() {
const firstLine = readFileSync(runtimePath, 'utf-8').split(/\\r?\\n/, 1)[0] ?? '';
if (!firstLine.startsWith('#!')) throw new Error('runtime is missing an absolute shebang');
const executable = firstLine.slice(2).trim();
if (!isAbsolute(executable)) throw new Error('runtime shebang executable must be absolute');
try {
if (!statSync(executable).isFile()) throw new Error('path is not a file');
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error('runtime shebang executable is unavailable: ' + message, { cause: error });
}
return executable;
}
function runRuntime(input) {
return new Promise((resolve, reject) => {
const child = spawn(resolveRuntimeExecutable(), [runtimePath], {
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
const stdout = [];
const stderr = [];
let stdinError;
child.stdout.on('data', (chunk) => stdout.push(chunk));
child.stderr.on('data', (chunk) => stderr.push(chunk));
child.stdin.on('error', (error) => {
if (error?.code !== 'EPIPE') stdinError = error;
});
child.once('error', reject);
child.once('close', (code, signal) => {
if (stdinError) {
reject(stdinError);
return;
}
resolve({
code,
signal,
stdout: Buffer.concat(stdout).toString('utf-8'),
stderr: Buffer.concat(stderr).toString('utf-8'),
});
});
child.stdin.end(input);
});
}
async function main() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
const result = await runRuntime(Buffer.concat(chunks));
if (result.stdout) process.stderr.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
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');
return;
}
if (result.signal) throw new Error('runtime terminated by signal ' + result.signal);
if (result.code !== 0) throw new Error('runtime exited with code ' + result.code);
}
main().catch((error) => {
const message = error instanceof Error ? error.stack || error.message : String(error);
process.stderr.write('Elydora Cline ' + hookKind + ' wrapper failed: ' + message + '\\n');
process.exitCode = 1;
});
"""
return (
template.replace("__METADATA_MARKER__", _METADATA_MARKER)
.replace("__METADATA__", _encode_metadata(metadata))
.replace("__HOOK_KIND__", json.dumps(metadata.kind))
.replace("__RUNTIME_PATH__", json.dumps(metadata.runtime_path))
)
def _decode_metadata(encoded: str) -> JsonObject:
padding = "=" * (-len(encoded) % 4)
try:
raw = base64.urlsafe_b64decode((encoded + padding).encode("ascii"))
value = json.loads(raw.decode("utf-8"))
except (ValueError, UnicodeError, json.JSONDecodeError) as error:
raise ValueError(f"invalid encoded metadata: {error}") from error
if not isinstance(value, dict):
raise ValueError("metadata must be an object")
return value
def _validate_metadata(value: JsonObject) -> HookMetadata:
if set(value) != {"version", "kind", "agentId", "runtimePath"}:
raise ValueError("metadata contains an unexpected field set")
version = value["version"]
kind = value["kind"]
agent_id = value["agentId"]
runtime_path = value["runtimePath"]
if isinstance(version, bool) or version != _METADATA_VERSION:
raise ValueError("metadata version must be 1")
if kind not in {"guard", "audit"}:
raise ValueError('metadata kind must be "guard" or "audit"')
if not isinstance(agent_id, str) or not agent_id:
raise ValueError("metadata agentId must be a non-empty string")
if not isinstance(runtime_path, str) or not os.path.isabs(runtime_path):
raise ValueError("metadata runtimePath must be an absolute path")
return HookMetadata(version, kind, agent_id, runtime_path)
def parse_metadata(file_path: str, source: str) -> Optional[HookMetadata]:
lines = source.splitlines()
marker_line = lines[1] if len(lines) > 1 else ""
if not marker_line.startswith(_METADATA_MARKER):
return None
try:
encoded = marker_line[len(_METADATA_MARKER):]
return _validate_metadata(_decode_metadata(encoded))
except ValueError as error:
raise ValueError(
f"Failed to parse Elydora Cline hook metadata at {file_path}: {error}"
) from error
def assert_wrapper_integrity(file: HookFile) -> None:
if file.metadata is None or file.source is None:
return
if file.source != build_wrapper(file.metadata):
raise ValueError(
f"Elydora Cline hook at {file.file_path} does not match the managed template"
)
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,
) -> Optional[RuntimeContract]:
if guard_file.metadata is None or audit_file.metadata is None:
return None
assert_wrapper_integrity(guard_file)
assert_wrapper_integrity(audit_file)
guard = guard_file.metadata
audit = audit_file.metadata
if guard.kind != "guard" or audit.kind != "audit":
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)
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(
audit.runtime_path, expected_audit
):
raise ValueError(
"Elydora Cline hook metadata references an unexpected runtime path"
)
return RuntimeContract(
agent_id=guard.agent_id,
agent_directory=agent_directory,
guard_path=expected_guard,
audit_path=expected_audit,
)
+194
View File
@@ -0,0 +1,194 @@
"""Fail-fast Cline hook I/O and runtime validation."""
from __future__ import annotations
from dataclasses import dataclass
import os
import tempfile
from typing import List, Sequence, Tuple
from ._file_io import (
read_json,
regular_file_exists,
remove_file,
require_runtime,
write_text_atomic,
)
from .cline_contract import (
AGENT_KEY,
HookFile,
RuntimeContract,
parse_metadata,
same_agent_id,
)
@dataclass(frozen=True)
class PendingWrite:
state: HookFile
source: str
@dataclass(frozen=True)
class StagedFile:
state: HookFile
temporary_path: str
def read_hook_file(file_path: str) -> HookFile:
try:
with open(file_path, "r", encoding="utf-8") as file:
source = file.read()
except FileNotFoundError:
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),
)
def require_available_hook_file(file: HookFile) -> None:
if file.exists and file.metadata is None:
raise ValueError(
f"Cline hook at {file.file_path} already exists and is owned "
"by another integration"
)
def _remove_temporary(path: str) -> 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,
)
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}"
) from error
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",
)
else:
remove_file(state.file_path, "Cline hook rollback")
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 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 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:
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)
):
return False
files: Tuple[Tuple[str, str], ...] = (
(contract.guard_path, "Elydora guard runtime"),
(contract.audit_path, "Elydora audit runtime"),
)
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",
]
+17 -3
View File
@@ -206,9 +206,23 @@ def main():
session_id = "unknown"
if isinstance(event, dict):
tool_name = event.get("tool_name", event.get("toolName", event.get("name", "unknown")))
tool_input = event.get("tool_input", event.get("toolInput", event.get("input", {{}})))
session_id = event.get("session_id", event.get("sessionId", event.get("session", "unknown")))
cline_event = event.get("tool_result")
if not isinstance(cline_event, dict):
cline_event = event.get("tool_call")
if not isinstance(cline_event, dict):
cline_event = {{}}
tool_name = event.get(
"tool_name",
event.get("toolName", event.get("name", cline_event.get("name", "unknown"))),
)
tool_input = event.get(
"tool_input",
event.get("toolInput", event.get("input", cline_event.get("input", {{}}))),
)
session_id = event.get(
"session_id",
event.get("sessionId", event.get("session", event.get("taskId", "unknown"))),
)
# Read chain state
prev_chain_hash = read_chain_state()
+5
View File
@@ -21,6 +21,11 @@ SUPPORTED_AGENTS: Dict[str, Dict[str, str]] = {
"hook_event": "PreToolUse/PostToolUse",
"config_path": "~/.codex/hooks.json",
},
"cline": {
"name": "Cline",
"hook_event": "PreToolUse/PostToolUse",
"config_path": "~/.cline/hooks/PreToolUse.mjs",
},
"copilot": {
"name": "Copilot CLI",
"hook_event": "PostToolUse",