fix(letta): harden official Python hook integration
This commit is contained in:
1 parent
231cda604e
commit
909f3dd106
19 files changed
+2443
-212
No files matched your search
+57
-187
@@ -1,208 +1,78 @@
|
||||
"""Letta Code plugin — merges PreToolUse/PostToolUse hooks into ~/.letta/settings.json."""
|
||||
"""Letta Code 0.28 native global hook integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from typing import Dict
|
||||
|
||||
from ._file_io import write_json_atomic, write_text_atomic
|
||||
from .base import AgentPlugin, InstallConfig, PluginStatus
|
||||
from .hook_template import generate_hook_script
|
||||
from .letta_config import render_letta_document
|
||||
from .letta_contract import (
|
||||
AGENT_KEY,
|
||||
JsonObject,
|
||||
build_letta_group,
|
||||
letta_runtime_contracts,
|
||||
)
|
||||
from .letta_installation import (
|
||||
LettaRuntimePaths,
|
||||
commit_letta_installation,
|
||||
commit_letta_uninstall,
|
||||
preflight_letta_installation,
|
||||
prepare_letta_installation,
|
||||
prepare_letta_uninstall,
|
||||
)
|
||||
from .letta_io import letta_runtime_files_exist
|
||||
from .letta_sources import read_letta_sources
|
||||
|
||||
|
||||
SETTINGS_PATH = os.path.join(os.path.expanduser("~"), ".letta", "settings.json")
|
||||
ELYDORA_DIR = os.path.join(os.path.expanduser("~"), ".elydora")
|
||||
def _installed_groups(paths: LettaRuntimePaths) -> Dict[str, JsonObject]:
|
||||
return {
|
||||
"PreToolUse": build_letta_group(paths.guard_path),
|
||||
"PostToolUse": build_letta_group(paths.audit_path),
|
||||
"PostToolUseFailure": build_letta_group(paths.audit_path),
|
||||
}
|
||||
|
||||
|
||||
class LettaPlugin(AgentPlugin):
|
||||
"""Install/uninstall Elydora audit hook for Letta Code."""
|
||||
"""Install Elydora into Letta Code's native global settings."""
|
||||
|
||||
@staticmethod
|
||||
def _hook_path_for(agent_id: str) -> str:
|
||||
return os.path.join(ELYDORA_DIR, agent_id, "hook.py")
|
||||
manages_guard_runtime = True
|
||||
|
||||
def preflight_install(self, config: InstallConfig) -> None:
|
||||
sources = read_letta_sources()
|
||||
preflight_letta_installation(config, sources)
|
||||
|
||||
def install(self, config: InstallConfig) -> None:
|
||||
agent_id = config.get("agent_id", "")
|
||||
agent_name = config.get("agent_name", "")
|
||||
|
||||
# Create per-agent directory
|
||||
agent_dir = os.path.join(ELYDORA_DIR, agent_id)
|
||||
os.makedirs(agent_dir, exist_ok=True)
|
||||
|
||||
# Write config.json
|
||||
config_data = {
|
||||
"org_id": config.get("org_id", ""),
|
||||
"agent_id": agent_id,
|
||||
"kid": config.get("kid", ""),
|
||||
"base_url": config.get("base_url", "https://api.elydora.com"),
|
||||
"token": config.get("token", ""),
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
config_path = os.path.join(agent_dir, "config.json")
|
||||
write_json_atomic(
|
||||
config_path,
|
||||
config_data,
|
||||
0o600,
|
||||
"Elydora runtime config",
|
||||
sources = read_letta_sources()
|
||||
paths = preflight_letta_installation(config, sources)
|
||||
rendered = render_letta_document(
|
||||
sources.global_settings,
|
||||
None,
|
||||
_installed_groups(paths),
|
||||
)
|
||||
|
||||
# Write private key
|
||||
private_key_path = os.path.join(agent_dir, "private.key")
|
||||
write_text_atomic(
|
||||
private_key_path,
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
"Elydora private key",
|
||||
)
|
||||
|
||||
script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=agent_id,
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
)
|
||||
hook_path = self._hook_path_for(agent_id)
|
||||
write_text_atomic(
|
||||
hook_path,
|
||||
script,
|
||||
0o700,
|
||||
"Elydora audit runtime",
|
||||
)
|
||||
|
||||
guard_script_path = config.get("guard_script_path", "")
|
||||
python_exe = sys.executable
|
||||
|
||||
settings = _load_json(SETTINGS_PATH)
|
||||
hooks = settings.setdefault("hooks", {})
|
||||
|
||||
# --- PreToolUse (guard — freeze enforcement, PascalCase with matcher, no timeout_ms) ---
|
||||
pre_tool_use = hooks.setdefault("PreToolUse", [])
|
||||
pre_tool_use[:] = [h for h in pre_tool_use if not _is_elydora_hook(h)]
|
||||
if guard_script_path:
|
||||
pre_tool_use.append({
|
||||
"matcher": "*",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": f'"{python_exe}" {guard_script_path}',
|
||||
}
|
||||
],
|
||||
})
|
||||
|
||||
# --- PostToolUse (audit logging, PascalCase with matcher, no timeout_ms) ---
|
||||
post_tool_use = hooks.setdefault("PostToolUse", [])
|
||||
|
||||
post_tool_use[:] = [h for h in post_tool_use if not _is_elydora_hook(h)]
|
||||
|
||||
post_tool_use.append({
|
||||
"matcher": "*",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": hook_path,
|
||||
}
|
||||
],
|
||||
})
|
||||
|
||||
_save_json(SETTINGS_PATH, settings)
|
||||
print("Elydora hook installed for Letta Code.")
|
||||
print(f" Hook script: {hook_path}")
|
||||
print(f" Settings: {SETTINGS_PATH}")
|
||||
changes = prepare_letta_installation(config, paths, rendered)
|
||||
commit_letta_installation(changes, sources)
|
||||
print(f"Letta Code hooks installed at {sources.global_settings.file_path}")
|
||||
print("Letta Code verification: run /hooks and restart active sessions.")
|
||||
|
||||
def uninstall(self, agent_id: str = "") -> None:
|
||||
if os.path.exists(SETTINGS_PATH):
|
||||
settings = _load_json(SETTINGS_PATH)
|
||||
hooks = settings.get("hooks", {})
|
||||
changed = False
|
||||
|
||||
# Remove PreToolUse entries
|
||||
pre_tool_use = hooks.get("PreToolUse", [])
|
||||
pre_filtered = [h for h in pre_tool_use if not _is_elydora_hook(h, agent_id)]
|
||||
if len(pre_filtered) != len(pre_tool_use):
|
||||
hooks["PreToolUse"] = pre_filtered
|
||||
if not pre_filtered:
|
||||
del hooks["PreToolUse"]
|
||||
changed = True
|
||||
|
||||
# Remove PostToolUse entries
|
||||
post_tool_use = hooks.get("PostToolUse", [])
|
||||
post_filtered = [h for h in post_tool_use if not _is_elydora_hook(h, agent_id)]
|
||||
if len(post_filtered) != len(post_tool_use):
|
||||
hooks["PostToolUse"] = post_filtered
|
||||
if not post_filtered:
|
||||
del hooks["PostToolUse"]
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
if not hooks:
|
||||
del settings["hooks"]
|
||||
_save_json(SETTINGS_PATH, settings)
|
||||
|
||||
# Hook script removal is handled by cli.py cmd_uninstall (rmtree of agent dir)
|
||||
print("Elydora hook uninstalled from Letta Code.")
|
||||
sources = read_letta_sources()
|
||||
rendered = render_letta_document(
|
||||
sources.global_settings, agent_id or None, {}
|
||||
)
|
||||
commit_letta_uninstall(prepare_letta_uninstall(rendered), sources)
|
||||
|
||||
def status(self) -> PluginStatus:
|
||||
# Scan ~/.elydora/*/hook.py for any installed hook
|
||||
import glob as _glob
|
||||
hook_pattern = os.path.join(ELYDORA_DIR, "*", "hook.py")
|
||||
hook_files = _glob.glob(hook_pattern)
|
||||
hook_exists = len(hook_files) > 0
|
||||
|
||||
settings_configured = False
|
||||
if os.path.exists(SETTINGS_PATH):
|
||||
settings = _load_json(SETTINGS_PATH)
|
||||
hooks = settings.get("hooks", {})
|
||||
pre_tool_use = hooks.get("PreToolUse", [])
|
||||
post_tool_use = hooks.get("PostToolUse", [])
|
||||
pre_configured = any(_is_elydora_hook(h) for h in pre_tool_use)
|
||||
post_configured = any(_is_elydora_hook(h) for h in post_tool_use)
|
||||
settings_configured = pre_configured and post_configured
|
||||
|
||||
installed = hook_exists and settings_configured
|
||||
sources = read_letta_sources()
|
||||
contracts = letta_runtime_contracts(sources.global_settings.hooks)
|
||||
configured = not sources.disable_control.disabled and bool(contracts)
|
||||
installed = configured and letta_runtime_files_exist(contracts)
|
||||
file_path = sources.global_settings.file_path
|
||||
if installed:
|
||||
details = f"Found {len(hook_files)} agent(s): {', '.join(hook_files)}"
|
||||
elif hook_exists:
|
||||
details = "Hook script exists but not configured in settings"
|
||||
elif settings_configured:
|
||||
details = "Configured in settings but hook script missing"
|
||||
details = f"Config: {file_path}"
|
||||
elif contracts and sources.disable_control.disabled:
|
||||
details = f"Configured hooks are disabled: {file_path}"
|
||||
elif contracts:
|
||||
details = f"Configured at {file_path}; managed contract incomplete"
|
||||
else:
|
||||
details = "Not installed"
|
||||
|
||||
return PluginStatus(installed=installed, agent="letta", details=details)
|
||||
|
||||
|
||||
def _is_elydora_hook(entry: dict, agent_id: str = "") -> bool:
|
||||
# Collect all command strings from the entry
|
||||
commands: list[str] = []
|
||||
inner_hooks = entry.get("hooks")
|
||||
if isinstance(inner_hooks, list):
|
||||
for hook in inner_hooks:
|
||||
if isinstance(hook, dict) and isinstance(hook.get("command"), str):
|
||||
commands.append(hook["command"])
|
||||
else:
|
||||
command = entry.get("command")
|
||||
if isinstance(command, str):
|
||||
commands.append(command)
|
||||
|
||||
for cmd in commands:
|
||||
cmd_lower = cmd.lower()
|
||||
if "elydora" not in cmd_lower:
|
||||
continue
|
||||
# If agent_id is specified, only match hooks for that specific agent
|
||||
if agent_id and agent_id in cmd:
|
||||
return True
|
||||
if not agent_id:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _load_json(path: str) -> dict:
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _save_json(path: str, data: dict) -> None:
|
||||
write_json_atomic(path, data, 0o600, "Letta settings")
|
||||
return PluginStatus(installed=installed, agent=AGENT_KEY, details=details)
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Letta Code command construction and exact runtime ownership."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from elydora._runtime_paths import runtime_root
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LettaRuntimeReference:
|
||||
agent_id: str
|
||||
script_path: str
|
||||
executable_path: Optional[str] = None
|
||||
|
||||
|
||||
def same_letta_path(left: str, right: str) -> bool:
|
||||
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(
|
||||
os.path.abspath(right)
|
||||
)
|
||||
|
||||
|
||||
def same_letta_agent_id(left: str, right: str) -> bool:
|
||||
return os.path.normcase(left) == os.path.normcase(right)
|
||||
|
||||
|
||||
def _quote_posix(value: str) -> str:
|
||||
return "'" + value.replace("'", "'\"'\"'") + "'"
|
||||
|
||||
|
||||
def _quote_powershell(value: str) -> str:
|
||||
return "'" + value.replace("'", "''") + "'"
|
||||
|
||||
|
||||
def build_letta_command(script_path: str) -> str:
|
||||
if not os.path.isabs(sys.executable) or not os.path.isabs(script_path):
|
||||
raise ValueError(
|
||||
"Letta Code hook commands require absolute executable and script paths"
|
||||
)
|
||||
invocation = (
|
||||
f"{_quote_powershell(sys.executable)} {_quote_powershell(script_path)}"
|
||||
if os.name == "nt"
|
||||
else f"{_quote_posix(sys.executable)} {_quote_posix(script_path)}"
|
||||
)
|
||||
return f"& {invocation}; exit $LASTEXITCODE" if os.name == "nt" else invocation
|
||||
|
||||
|
||||
def _read_posix_argument(command: str, start: int) -> Optional[Tuple[str, int]]:
|
||||
if start >= len(command) or command[start] != "'":
|
||||
return None
|
||||
apostrophe = "'\"'\"'"
|
||||
value = ""
|
||||
index = start + 1
|
||||
while index < len(command):
|
||||
if command.startswith(apostrophe, index):
|
||||
value += "'"
|
||||
index += len(apostrophe)
|
||||
continue
|
||||
if command[index] == "'":
|
||||
return value, index + 1
|
||||
value += command[index]
|
||||
index += 1
|
||||
return None
|
||||
|
||||
|
||||
def _parse_posix_command(command: str) -> Optional[Tuple[str, str]]:
|
||||
executable = _read_posix_argument(command, 0)
|
||||
if executable is None or executable[1] >= len(command):
|
||||
return None
|
||||
if command[executable[1]] != " ":
|
||||
return None
|
||||
script = _read_posix_argument(command, executable[1] + 1)
|
||||
if script is None or script[1] != len(command):
|
||||
return None
|
||||
return executable[0], script[0]
|
||||
|
||||
|
||||
def _read_powershell_argument(
|
||||
command: str, start: int
|
||||
) -> Optional[Tuple[str, int]]:
|
||||
if start >= len(command) or command[start] != "'":
|
||||
return None
|
||||
value = ""
|
||||
index = start + 1
|
||||
while index < len(command):
|
||||
if command[index] != "'":
|
||||
value += command[index]
|
||||
index += 1
|
||||
continue
|
||||
if index + 1 < len(command) and command[index + 1] == "'":
|
||||
value += "'"
|
||||
index += 2
|
||||
continue
|
||||
return value, index + 1
|
||||
return None
|
||||
|
||||
|
||||
def _parse_powershell_command(command: str) -> Optional[Tuple[str, str]]:
|
||||
if not command.startswith("& "):
|
||||
return None
|
||||
executable = _read_powershell_argument(command, 2)
|
||||
if executable is None or executable[1] >= len(command):
|
||||
return None
|
||||
if command[executable[1]] != " ":
|
||||
return None
|
||||
script = _read_powershell_argument(command, executable[1] + 1)
|
||||
if script is None or command[script[1] :] != "; exit $LASTEXITCODE":
|
||||
return None
|
||||
return executable[0], script[0]
|
||||
|
||||
|
||||
def _is_python_executable(file_path: str) -> bool:
|
||||
return bool(re.fullmatch(r"python(?:3(?:\.\d+)?)?(?:\.exe)?", os.path.basename(file_path), re.IGNORECASE))
|
||||
|
||||
|
||||
def _runtime_reference(
|
||||
script_path: str,
|
||||
script_name: str,
|
||||
executable_path: Optional[str] = None,
|
||||
) -> Optional[LettaRuntimeReference]:
|
||||
if not os.path.isabs(script_path) or os.path.basename(script_path) != script_name:
|
||||
return None
|
||||
agent_directory = os.path.dirname(script_path)
|
||||
if not same_letta_path(os.path.dirname(agent_directory), runtime_root()):
|
||||
return None
|
||||
agent_id = os.path.basename(agent_directory)
|
||||
if agent_id in {"", ".", ".."}:
|
||||
return None
|
||||
return LettaRuntimeReference(agent_id, script_path, executable_path)
|
||||
|
||||
|
||||
def letta_runtime_reference(
|
||||
command: str, script_name: str
|
||||
) -> Optional[LettaRuntimeReference]:
|
||||
parsed = (
|
||||
_parse_powershell_command(command)
|
||||
if os.name == "nt"
|
||||
else _parse_posix_command(command)
|
||||
)
|
||||
if (
|
||||
parsed is None
|
||||
or not os.path.isabs(parsed[0])
|
||||
or not _is_python_executable(parsed[0])
|
||||
):
|
||||
return None
|
||||
return _runtime_reference(parsed[1], script_name, parsed[0])
|
||||
|
||||
|
||||
def letta_legacy_guard_reference(
|
||||
command: str, script_name: str
|
||||
) -> Optional[LettaRuntimeReference]:
|
||||
if not command.startswith('"'):
|
||||
return None
|
||||
closing = command.find('"', 1)
|
||||
if closing < 0 or closing + 1 >= len(command) or command[closing + 1] != " ":
|
||||
return None
|
||||
executable = command[1:closing]
|
||||
script_path = command[closing + 2 :]
|
||||
if (
|
||||
not os.path.isabs(executable)
|
||||
or not _is_python_executable(executable)
|
||||
or not script_path
|
||||
):
|
||||
return None
|
||||
return _runtime_reference(script_path, script_name, executable)
|
||||
|
||||
|
||||
def letta_legacy_audit_reference(
|
||||
command: str, script_name: str
|
||||
) -> Optional[LettaRuntimeReference]:
|
||||
return _runtime_reference(command, script_name)
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Strict Letta Code settings parsing and source-preserving edits."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Optional
|
||||
|
||||
from ._jsonc import JsoncEditor
|
||||
from ._managed_files import FileSnapshot
|
||||
from ._strict_json import parse_json_object
|
||||
from .letta_contract import (
|
||||
MANAGED_EVENTS,
|
||||
JsonObject,
|
||||
LettaHooks,
|
||||
managed_letta_removals,
|
||||
read_letta_hooks,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LettaDocument:
|
||||
kind: str
|
||||
file_path: str
|
||||
exists: bool
|
||||
raw: str
|
||||
snapshot: Optional[FileSnapshot]
|
||||
root: JsonObject
|
||||
hooks: LettaHooks
|
||||
has_hooks_container: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RenderedLettaDocument:
|
||||
document: LettaDocument
|
||||
changed: bool
|
||||
next_source: Optional[str]
|
||||
|
||||
|
||||
def letta_source_label(kind: str) -> str:
|
||||
labels = {
|
||||
"global": "Letta Code global settings",
|
||||
"project": "Letta Code project settings",
|
||||
"project-local": "Letta Code project-local settings",
|
||||
}
|
||||
try:
|
||||
return labels[kind]
|
||||
except KeyError as error:
|
||||
raise ValueError(f"Unsupported Letta Code document kind: {kind}") from error
|
||||
|
||||
|
||||
def letta_document_label(document: LettaDocument) -> str:
|
||||
return letta_source_label(document.kind)
|
||||
|
||||
|
||||
def parse_letta_document(
|
||||
*,
|
||||
kind: str,
|
||||
exists: bool,
|
||||
file_path: str,
|
||||
raw: str,
|
||||
snapshot: Optional[FileSnapshot] = None,
|
||||
) -> LettaDocument:
|
||||
label = f"{letta_source_label(kind)} at {file_path}"
|
||||
root = parse_json_object(raw, label)
|
||||
return LettaDocument(
|
||||
kind,
|
||||
file_path,
|
||||
exists,
|
||||
raw,
|
||||
snapshot,
|
||||
root,
|
||||
read_letta_hooks(root["hooks"]) if "hooks" in root else {},
|
||||
"hooks" in root,
|
||||
)
|
||||
|
||||
|
||||
def create_letta_document(kind: str, file_path: str) -> LettaDocument:
|
||||
return parse_letta_document(
|
||||
kind=kind,
|
||||
exists=False,
|
||||
file_path=file_path,
|
||||
raw="{}\n",
|
||||
)
|
||||
|
||||
|
||||
def _current_document(
|
||||
document: LettaDocument, editor: JsoncEditor
|
||||
) -> LettaDocument:
|
||||
return parse_letta_document(
|
||||
kind=document.kind,
|
||||
exists=document.exists,
|
||||
file_path=document.file_path,
|
||||
raw=editor.raw,
|
||||
snapshot=document.snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _event_groups(hooks: LettaHooks, event: str) -> list[JsonObject]:
|
||||
value = hooks.get(event)
|
||||
return value if isinstance(value, list) else []
|
||||
|
||||
|
||||
def _remove_managed(
|
||||
editor: JsoncEditor,
|
||||
document: LettaDocument,
|
||||
agent_id: Optional[str],
|
||||
) -> None:
|
||||
removals = managed_letta_removals(document.hooks, agent_id)
|
||||
for event in MANAGED_EVENTS:
|
||||
event_removals = sorted(
|
||||
(item for item in removals if item.event == event),
|
||||
key=lambda item: item.group_index,
|
||||
reverse=True,
|
||||
)
|
||||
for removal in event_removals:
|
||||
group_path = ("hooks", event, removal.group_index)
|
||||
if removal.remove_group:
|
||||
editor.delete(group_path)
|
||||
continue
|
||||
for handler_index in sorted(removal.handler_indexes, reverse=True):
|
||||
editor.delete((*group_path, "hooks", handler_index))
|
||||
if event_removals:
|
||||
current = _current_document(document, editor)
|
||||
if event in current.hooks and not _event_groups(current.hooks, event):
|
||||
editor.delete(("hooks", event))
|
||||
current = _current_document(document, editor)
|
||||
if current.has_hooks_container and not current.hooks:
|
||||
editor.delete(("hooks",))
|
||||
|
||||
|
||||
def _append_group(
|
||||
editor: JsoncEditor,
|
||||
document: LettaDocument,
|
||||
event: str,
|
||||
group: JsonObject,
|
||||
) -> None:
|
||||
current = _current_document(document, editor)
|
||||
groups = _event_groups(current.hooks, event)
|
||||
if not current.has_hooks_container:
|
||||
editor.add_property((), "hooks", {event: [group]})
|
||||
elif groups:
|
||||
editor.append(("hooks", event), group)
|
||||
elif event in current.hooks:
|
||||
editor.append(("hooks", event), group)
|
||||
else:
|
||||
editor.add_property(("hooks",), event, [group])
|
||||
|
||||
|
||||
def _already_installed(
|
||||
document: LettaDocument, additions: Dict[str, JsonObject]
|
||||
) -> bool:
|
||||
if set(additions) != set(MANAGED_EVENTS):
|
||||
return False
|
||||
removals = managed_letta_removals(document.hooks)
|
||||
for event in MANAGED_EVENTS:
|
||||
expected = additions[event]
|
||||
event_removals = [item for item in removals if item.event == event]
|
||||
exact_groups = [
|
||||
group for group in _event_groups(document.hooks, event)
|
||||
if group == expected
|
||||
]
|
||||
if (
|
||||
len(event_removals) != 1
|
||||
or not event_removals[0].remove_group
|
||||
or len(exact_groups) != 1
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def render_letta_document(
|
||||
document: LettaDocument,
|
||||
agent_id: Optional[str],
|
||||
additions: Dict[str, JsonObject],
|
||||
) -> RenderedLettaDocument:
|
||||
if agent_id is None and _already_installed(document, additions):
|
||||
return RenderedLettaDocument(document, False, document.raw)
|
||||
editor = JsoncEditor(
|
||||
document.raw,
|
||||
f"{letta_document_label(document)} at {document.file_path}",
|
||||
allow_trailing_commas=False,
|
||||
)
|
||||
_remove_managed(editor, document, agent_id)
|
||||
for event in MANAGED_EVENTS:
|
||||
group = additions.get(event)
|
||||
if group is not None:
|
||||
_append_group(editor, document, event, group)
|
||||
current = _current_document(document, editor)
|
||||
if not additions and not current.root:
|
||||
return RenderedLettaDocument(document, True, None)
|
||||
return RenderedLettaDocument(
|
||||
document,
|
||||
editor.raw != document.raw,
|
||||
editor.raw,
|
||||
)
|
||||
@@ -0,0 +1,277 @@
|
||||
"""Letta Code 0.28 hook schema and exact ownership rules."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from elydora._runtime_paths import runtime_root
|
||||
|
||||
from .letta_command import (
|
||||
LettaRuntimeReference,
|
||||
build_letta_command,
|
||||
letta_legacy_audit_reference,
|
||||
letta_legacy_guard_reference,
|
||||
letta_runtime_reference,
|
||||
same_letta_agent_id,
|
||||
same_letta_path,
|
||||
)
|
||||
|
||||
|
||||
AGENT_KEY = "letta"
|
||||
GUARD_SCRIPT = "guard.py"
|
||||
AUDIT_SCRIPT = "hook.py"
|
||||
HOOK_TIMEOUT_MILLISECONDS = 10_000
|
||||
MANAGED_EVENTS = ("PreToolUse", "PostToolUse", "PostToolUseFailure")
|
||||
|
||||
TOOL_EVENTS = {
|
||||
"PreToolUse",
|
||||
"PostToolUse",
|
||||
"PostToolUseFailure",
|
||||
"PermissionRequest",
|
||||
}
|
||||
SIMPLE_EVENTS = {
|
||||
"UserPromptSubmit",
|
||||
"Notification",
|
||||
"Stop",
|
||||
"SubagentStop",
|
||||
"PreCompact",
|
||||
"SessionStart",
|
||||
"SessionEnd",
|
||||
}
|
||||
KNOWN_EVENTS = TOOL_EVENTS | SIMPLE_EVENTS
|
||||
|
||||
JsonObject = Dict[str, Any]
|
||||
LettaHooks = Dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LettaRuntimeContract:
|
||||
agent_id: str
|
||||
guard_path: str
|
||||
audit_path: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ManagedRemoval:
|
||||
event: str
|
||||
group_index: int
|
||||
handler_indexes: Tuple[int, ...]
|
||||
remove_group: bool
|
||||
|
||||
|
||||
def elydora_dir() -> str:
|
||||
return runtime_root()
|
||||
|
||||
|
||||
def _validate_timeout(value: JsonObject, label: str) -> None:
|
||||
if "timeout" not in value:
|
||||
return
|
||||
timeout = value["timeout"]
|
||||
try:
|
||||
finite = math.isfinite(timeout)
|
||||
except (TypeError, OverflowError):
|
||||
finite = False
|
||||
if (
|
||||
isinstance(timeout, bool)
|
||||
or not isinstance(timeout, (int, float))
|
||||
or not finite
|
||||
or timeout < 0
|
||||
):
|
||||
raise ValueError(f"{label} timeout must be a non-negative finite number")
|
||||
|
||||
|
||||
def _validate_handler(value: Any, label: str) -> JsonObject:
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f"{label} must be an object")
|
||||
handler = dict(value)
|
||||
kind = handler.get("type")
|
||||
if kind not in {"command", "prompt"}:
|
||||
raise ValueError(f'{label} has unsupported type "{kind}"')
|
||||
_validate_timeout(handler, label)
|
||||
if "quiet" in handler and not isinstance(handler["quiet"], bool):
|
||||
raise ValueError(f"{label} quiet must be a boolean")
|
||||
if kind == "command":
|
||||
command = handler.get("command")
|
||||
if not isinstance(command, str) or not command:
|
||||
raise ValueError(f"{label} requires a non-empty command")
|
||||
else:
|
||||
prompt = handler.get("prompt")
|
||||
if not isinstance(prompt, str) or not prompt:
|
||||
raise ValueError(f"{label} requires a non-empty prompt")
|
||||
if "model" in handler and not isinstance(handler["model"], str):
|
||||
raise ValueError(f"{label} model must be a string")
|
||||
return handler
|
||||
|
||||
|
||||
def _validate_group(value: Any, event: str, index: int) -> JsonObject:
|
||||
label = f"Letta Code settings group hooks.{event}[{index}]"
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f"{label} must be an object")
|
||||
group = dict(value)
|
||||
if event in TOOL_EVENTS:
|
||||
if not isinstance(group.get("matcher"), str):
|
||||
raise ValueError(f"{label} matcher must be a string")
|
||||
elif "matcher" in group:
|
||||
raise ValueError(f"{label} matcher is unsupported 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, f"{label}.hooks[{handler_index}]")
|
||||
for handler_index, handler in enumerate(handlers)
|
||||
]
|
||||
return group
|
||||
|
||||
|
||||
def read_letta_hooks(value: Any) -> LettaHooks:
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError('Letta Code settings field "hooks" must be an object')
|
||||
if "disabled" in value and not isinstance(value["disabled"], bool):
|
||||
raise ValueError(
|
||||
'Letta Code settings field "hooks.disabled" must be a boolean'
|
||||
)
|
||||
hooks: LettaHooks = {}
|
||||
for event, groups in value.items():
|
||||
if event == "disabled" or event not in KNOWN_EVENTS:
|
||||
hooks[event] = groups
|
||||
continue
|
||||
if not isinstance(groups, list):
|
||||
raise ValueError(
|
||||
f'Letta Code settings field "hooks.{event}" must be an array'
|
||||
)
|
||||
hooks[event] = [
|
||||
_validate_group(group, event, index)
|
||||
for index, group in enumerate(groups)
|
||||
]
|
||||
return hooks
|
||||
|
||||
|
||||
def build_letta_group(script_path: str) -> JsonObject:
|
||||
return {
|
||||
"matcher": "*",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": build_letta_command(script_path),
|
||||
"timeout": HOOK_TIMEOUT_MILLISECONDS,
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
def _exact_group(group: JsonObject) -> bool:
|
||||
return set(group) == {"matcher", "hooks"} and group.get("matcher") == "*"
|
||||
|
||||
|
||||
def _current_reference(
|
||||
handler: JsonObject, script_name: str
|
||||
) -> Optional[LettaRuntimeReference]:
|
||||
if (
|
||||
set(handler) == {"type", "command", "timeout"}
|
||||
and handler.get("type") == "command"
|
||||
and handler.get("timeout") == HOOK_TIMEOUT_MILLISECONDS
|
||||
and isinstance(handler.get("command"), str)
|
||||
):
|
||||
return letta_runtime_reference(handler["command"], script_name)
|
||||
return None
|
||||
|
||||
|
||||
def _legacy_reference(
|
||||
event: str, handler: JsonObject, script_name: str
|
||||
) -> Optional[LettaRuntimeReference]:
|
||||
if (
|
||||
set(handler) != {"type", "command"}
|
||||
or handler.get("type") != "command"
|
||||
or not isinstance(handler.get("command"), str)
|
||||
):
|
||||
return None
|
||||
if event == "PreToolUse":
|
||||
return letta_legacy_guard_reference(handler["command"], script_name)
|
||||
return letta_legacy_audit_reference(handler["command"], script_name)
|
||||
|
||||
|
||||
def _event_groups(hooks: LettaHooks, event: str) -> List[JsonObject]:
|
||||
value = hooks.get(event)
|
||||
return value if isinstance(value, list) else []
|
||||
|
||||
|
||||
_EVENT_CONTRACTS = (
|
||||
("PreToolUse", GUARD_SCRIPT),
|
||||
("PostToolUse", AUDIT_SCRIPT),
|
||||
("PostToolUseFailure", AUDIT_SCRIPT),
|
||||
)
|
||||
|
||||
|
||||
def managed_letta_removals(
|
||||
hooks: LettaHooks, agent_id: Optional[str] = None
|
||||
) -> List[ManagedRemoval]:
|
||||
removals: List[ManagedRemoval] = []
|
||||
for event, script_name in _EVENT_CONTRACTS:
|
||||
for group_index, group in enumerate(_event_groups(hooks, event)):
|
||||
indexes = tuple(
|
||||
index
|
||||
for index, handler in enumerate(group["hooks"])
|
||||
if (
|
||||
reference := (
|
||||
_current_reference(handler, script_name)
|
||||
or _legacy_reference(event, handler, script_name)
|
||||
)
|
||||
)
|
||||
is not None
|
||||
and (
|
||||
agent_id is None
|
||||
or same_letta_agent_id(reference.agent_id, agent_id)
|
||||
)
|
||||
)
|
||||
if indexes:
|
||||
removals.append(ManagedRemoval(
|
||||
event,
|
||||
group_index,
|
||||
indexes,
|
||||
_exact_group(group) and len(indexes) == len(group["hooks"]),
|
||||
))
|
||||
return removals
|
||||
|
||||
|
||||
def _references_for_event(
|
||||
groups: List[JsonObject], script_name: str
|
||||
) -> Dict[str, List[LettaRuntimeReference]]:
|
||||
references: Dict[str, List[LettaRuntimeReference]] = {}
|
||||
for group in groups:
|
||||
if not _exact_group(group):
|
||||
continue
|
||||
for handler in group["hooks"]:
|
||||
reference = _current_reference(handler, script_name)
|
||||
if (
|
||||
reference is None
|
||||
or reference.executable_path is None
|
||||
or not same_letta_path(reference.executable_path, sys.executable)
|
||||
):
|
||||
continue
|
||||
key = os.path.normcase(reference.agent_id)
|
||||
references.setdefault(key, []).append(reference)
|
||||
return references
|
||||
|
||||
|
||||
def letta_runtime_contracts(hooks: LettaHooks) -> List[LettaRuntimeContract]:
|
||||
guards = _references_for_event(_event_groups(hooks, "PreToolUse"), GUARD_SCRIPT)
|
||||
posts = _references_for_event(_event_groups(hooks, "PostToolUse"), AUDIT_SCRIPT)
|
||||
failures = _references_for_event(
|
||||
_event_groups(hooks, "PostToolUseFailure"), AUDIT_SCRIPT
|
||||
)
|
||||
contracts: List[LettaRuntimeContract] = []
|
||||
for key, guard in guards.items():
|
||||
post = posts.get(key, [])
|
||||
failure = failures.get(key, [])
|
||||
if len(guard) != 1 or len(post) != 1 or len(failure) != 1:
|
||||
continue
|
||||
if not same_letta_path(post[0].script_path, failure[0].script_path):
|
||||
continue
|
||||
contracts.append(LettaRuntimeContract(
|
||||
guard[0].agent_id,
|
||||
guard[0].script_path,
|
||||
post[0].script_path,
|
||||
))
|
||||
return contracts
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Transactional Letta Code hook and runtime installation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import os
|
||||
from typing import List, Optional, Sequence
|
||||
|
||||
from elydora._runtime_paths import resolve_agent_directory
|
||||
|
||||
from ._managed_files import MAX_CONFIG_BYTES, MAX_SECRET_BYTES, MAX_SOURCE_BYTES
|
||||
from ._transaction import (
|
||||
FileChange,
|
||||
FilePrecondition,
|
||||
file_change,
|
||||
source_change,
|
||||
write_changes,
|
||||
)
|
||||
from .base import InstallConfig
|
||||
from .guard_template import generate_guard_script
|
||||
from .hook_template import generate_hook_script
|
||||
from .letta_command import same_letta_path
|
||||
from .letta_config import RenderedLettaDocument, letta_document_label
|
||||
from .letta_contract import AGENT_KEY, AUDIT_SCRIPT, GUARD_SCRIPT, elydora_dir
|
||||
from .letta_io import validate_api_origin, validate_private_key, validate_runtime_tree
|
||||
from .letta_sources import LettaSources, require_letta_hooks_enabled
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LettaRuntimePaths:
|
||||
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) -> LettaRuntimePaths:
|
||||
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_letta_path(config.get("guard_script_path", ""), guard_path):
|
||||
raise ValueError(
|
||||
"Elydora guard runtime must use the managed agent directory: "
|
||||
f"{guard_path}"
|
||||
)
|
||||
return LettaRuntimePaths(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"Letta Code installation requires agent_name {AGENT_KEY}"
|
||||
)
|
||||
validate_private_key(config["private_key"])
|
||||
validate_api_origin(config["base_url"])
|
||||
if "token" in config:
|
||||
token = config["token"]
|
||||
if not isinstance(token, str) or not token:
|
||||
raise ValueError("token must be a non-empty string when provided")
|
||||
_agent_paths(config)
|
||||
|
||||
|
||||
def preflight_letta_installation(
|
||||
config: InstallConfig, sources: LettaSources
|
||||
) -> LettaRuntimePaths:
|
||||
require_letta_hooks_enabled(sources)
|
||||
_validate_install_config(config)
|
||||
paths = _agent_paths(config)
|
||||
validate_runtime_tree(paths.agent_directory, paths.agent_id)
|
||||
return paths
|
||||
|
||||
|
||||
def _runtime_change(
|
||||
file_path: str,
|
||||
label: str,
|
||||
next_source: str,
|
||||
mode: int,
|
||||
maximum_bytes: int = MAX_SOURCE_BYTES,
|
||||
) -> Optional[FileChange]:
|
||||
return file_change(file_path, label, next_source, mode, maximum_bytes)
|
||||
|
||||
|
||||
def _rendered_change(
|
||||
rendered: RenderedLettaDocument,
|
||||
) -> Optional[FileChange]:
|
||||
if not rendered.changed:
|
||||
return None
|
||||
return source_change(
|
||||
rendered.document.file_path,
|
||||
letta_document_label(rendered.document),
|
||||
rendered.document.raw if rendered.document.exists else None,
|
||||
rendered.next_source,
|
||||
0o600,
|
||||
MAX_SOURCE_BYTES,
|
||||
expected_snapshot=rendered.document.snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _present(changes: Sequence[Optional[FileChange]]) -> List[FileChange]:
|
||||
return [change for change in changes if change is not None]
|
||||
|
||||
|
||||
def prepare_letta_installation(
|
||||
config: InstallConfig,
|
||||
paths: LettaRuntimePaths,
|
||||
rendered: RenderedLettaDocument,
|
||||
) -> List[FileChange]:
|
||||
guard_script = generate_guard_script(AGENT_KEY, paths.agent_id)
|
||||
audit_script = generate_hook_script(
|
||||
org_id=config.get("org_id", ""),
|
||||
agent_id=paths.agent_id,
|
||||
kid=config.get("kid", ""),
|
||||
base_url=config.get("base_url", "https://api.elydora.com"),
|
||||
fail_closed=True,
|
||||
native_payload=True,
|
||||
agent_name=AGENT_KEY,
|
||||
)
|
||||
return _present([
|
||||
_runtime_change(
|
||||
paths.guard_path, "Elydora guard runtime", guard_script, 0o700
|
||||
),
|
||||
_runtime_change(
|
||||
os.path.join(paths.agent_directory, "config.json"),
|
||||
"Elydora runtime config",
|
||||
_json_source(_runtime_config(config, paths.agent_id)),
|
||||
0o600,
|
||||
MAX_CONFIG_BYTES,
|
||||
),
|
||||
_runtime_change(
|
||||
os.path.join(paths.agent_directory, "private.key"),
|
||||
"Elydora private key",
|
||||
config.get("private_key", ""),
|
||||
0o600,
|
||||
MAX_SECRET_BYTES,
|
||||
),
|
||||
_runtime_change(
|
||||
paths.audit_path, "Elydora audit runtime", audit_script, 0o700
|
||||
),
|
||||
_rendered_change(rendered),
|
||||
])
|
||||
|
||||
|
||||
def _read_only_preconditions(
|
||||
sources: LettaSources, changed_path: Optional[str]
|
||||
) -> List[FilePrecondition]:
|
||||
return [
|
||||
condition
|
||||
for condition in sources.preconditions
|
||||
if changed_path is None
|
||||
or not same_letta_path(condition.file_path, changed_path)
|
||||
]
|
||||
|
||||
|
||||
def commit_letta_installation(
|
||||
changes: List[FileChange], sources: LettaSources
|
||||
) -> None:
|
||||
write_changes(
|
||||
changes,
|
||||
"Install Letta Code hooks",
|
||||
_read_only_preconditions(sources, sources.global_settings.file_path),
|
||||
)
|
||||
|
||||
|
||||
def prepare_letta_uninstall(
|
||||
rendered: RenderedLettaDocument,
|
||||
) -> Optional[FileChange]:
|
||||
return _rendered_change(rendered)
|
||||
|
||||
|
||||
def commit_letta_uninstall(
|
||||
change: Optional[FileChange], sources: LettaSources
|
||||
) -> None:
|
||||
if change is None:
|
||||
return
|
||||
write_changes(
|
||||
[change],
|
||||
"Uninstall Letta Code hooks",
|
||||
_read_only_preconditions(sources, sources.global_settings.file_path),
|
||||
)
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Strict Letta Code managed runtime inspection."""
|
||||
|
||||
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 .guard_template import generate_guard_script
|
||||
from .hook_template import generate_hook_script
|
||||
from .letta_command import same_letta_agent_id, same_letta_path
|
||||
from .letta_contract import AGENT_KEY, LettaRuntimeContract, elydora_dir
|
||||
|
||||
|
||||
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_letta_agent_id(agent_id, expected_agent_id)
|
||||
or config.get("agent_name") != AGENT_KEY
|
||||
):
|
||||
raise ValueError(
|
||||
"Elydora runtime identity does not match Letta Code hooks: "
|
||||
f"{config_path}"
|
||||
)
|
||||
if "token" in config:
|
||||
_require_non_empty_string(config.get("token"), "token", config_path)
|
||||
base_url = _require_non_empty_string(
|
||||
config.get("base_url"), "base_url", config_path
|
||||
)
|
||||
validate_api_origin(base_url, "Elydora runtime config base_url")
|
||||
|
||||
|
||||
def _read_runtime_config(file_path: str) -> Optional[JsonObject]:
|
||||
snapshot = read_physical_file(
|
||||
file_path, "Elydora runtime config", MAX_CONFIG_BYTES
|
||||
)
|
||||
if snapshot is None:
|
||||
return None
|
||||
return parse_json_object(
|
||||
snapshot.contents, f"Elydora runtime config at {file_path}"
|
||||
)
|
||||
|
||||
|
||||
def validate_runtime_tree(agent_directory: str, agent_id: str) -> None:
|
||||
root = elydora_dir()
|
||||
if not physical_directory_exists(root, "Elydora runtime directory"):
|
||||
return
|
||||
if not physical_directory_exists(
|
||||
agent_directory, "Elydora agent runtime directory"
|
||||
):
|
||||
return
|
||||
config_path = os.path.join(agent_directory, "config.json")
|
||||
config = _read_runtime_config(config_path)
|
||||
artifacts = (
|
||||
("private.key", "Elydora private key"),
|
||||
("guard.py", "Elydora guard runtime"),
|
||||
("hook.py", "Elydora audit runtime"),
|
||||
("chain-state.json", "Elydora chain state"),
|
||||
("status-cache.json", "Elydora status cache"),
|
||||
("error.log", "Elydora error log"),
|
||||
)
|
||||
artifact_exists = any(
|
||||
physical_file_exists(os.path.join(agent_directory, name), label)
|
||||
for name, label in artifacts
|
||||
)
|
||||
if config is None:
|
||||
if artifact_exists:
|
||||
raise ValueError(
|
||||
"Elydora runtime identity cannot be verified without config.json: "
|
||||
f"{agent_directory}"
|
||||
)
|
||||
return
|
||||
configured_id = config.get("agent_id")
|
||||
if (
|
||||
not isinstance(configured_id, str)
|
||||
or not same_letta_agent_id(configured_id, agent_id)
|
||||
or config.get("agent_name") != AGENT_KEY
|
||||
):
|
||||
raise ValueError(
|
||||
"Elydora runtime config identity does not match Letta Code agent "
|
||||
f"{agent_id}: {config_path}"
|
||||
)
|
||||
|
||||
|
||||
def _runtime_contract_exists(contract: LettaRuntimeContract) -> bool:
|
||||
root = elydora_dir()
|
||||
agent_directory = os.path.dirname(contract.guard_path)
|
||||
if (
|
||||
not same_letta_path(os.path.dirname(agent_directory), root)
|
||||
or not same_letta_path(
|
||||
contract.audit_path, os.path.join(agent_directory, "hook.py")
|
||||
)
|
||||
):
|
||||
return False
|
||||
if not physical_directory_exists(root, "Elydora runtime directory"):
|
||||
return False
|
||||
if not physical_directory_exists(
|
||||
agent_directory, "Elydora agent runtime directory"
|
||||
):
|
||||
return False
|
||||
config_path = os.path.join(agent_directory, "config.json")
|
||||
key_path = os.path.join(agent_directory, "private.key")
|
||||
config = _read_runtime_config(config_path)
|
||||
key = read_physical_file(key_path, "Elydora private key", MAX_SECRET_BYTES)
|
||||
guard = read_physical_file(contract.guard_path, "Elydora guard runtime")
|
||||
audit = read_physical_file(contract.audit_path, "Elydora audit runtime")
|
||||
if config is None or key is None or guard is None or audit is None:
|
||||
return False
|
||||
_validate_runtime_config(config, contract.agent_id, config_path)
|
||||
validate_private_key(key.contents, "Elydora private key")
|
||||
expected_guard = generate_guard_script(AGENT_KEY, contract.agent_id)
|
||||
expected_audit = generate_hook_script(
|
||||
org_id=str(config["org_id"]),
|
||||
agent_id=contract.agent_id,
|
||||
kid=str(config["kid"]),
|
||||
base_url=str(config["base_url"]),
|
||||
fail_closed=True,
|
||||
native_payload=True,
|
||||
agent_name=AGENT_KEY,
|
||||
)
|
||||
return guard.contents == expected_guard and audit.contents == expected_audit
|
||||
|
||||
|
||||
def letta_runtime_files_exist(
|
||||
contracts: List[LettaRuntimeContract],
|
||||
) -> bool:
|
||||
return any(_runtime_contract_exists(contract) for contract in contracts)
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Letta Code 0.28 settings discovery and effective hook controls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from typing import Dict, Optional, Tuple
|
||||
|
||||
from ._managed_files import (
|
||||
MAX_SOURCE_BYTES,
|
||||
physical_directory_exists,
|
||||
read_physical_file,
|
||||
)
|
||||
from ._transaction import FilePrecondition
|
||||
from .letta_command import same_letta_path
|
||||
from .letta_config import (
|
||||
LettaDocument,
|
||||
create_letta_document,
|
||||
letta_document_label,
|
||||
letta_source_label,
|
||||
parse_letta_document,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LettaDisableControl:
|
||||
disabled: bool
|
||||
source: Optional[LettaDocument]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LettaSources:
|
||||
home_directory: str
|
||||
global_settings: LettaDocument
|
||||
project: LettaDocument
|
||||
project_local: LettaDocument
|
||||
project_active: bool
|
||||
disable_control: LettaDisableControl
|
||||
preconditions: Tuple[FilePrecondition, ...]
|
||||
|
||||
|
||||
def _home_directory() -> str:
|
||||
home = os.environ.get("HOME") or os.path.expanduser("~")
|
||||
return os.path.abspath(home)
|
||||
|
||||
|
||||
def _comparison_path(file_path: str) -> str:
|
||||
return os.path.normcase(os.path.abspath(file_path))
|
||||
|
||||
|
||||
def _canonical_path(file_path: str) -> str:
|
||||
return os.path.realpath(file_path)
|
||||
|
||||
|
||||
def _read_document(kind: str, file_path: str) -> LettaDocument:
|
||||
snapshot = read_physical_file(
|
||||
file_path, letta_source_label(kind), MAX_SOURCE_BYTES
|
||||
)
|
||||
if snapshot is None:
|
||||
return create_letta_document(kind, file_path)
|
||||
return parse_letta_document(
|
||||
kind=kind,
|
||||
exists=True,
|
||||
file_path=file_path,
|
||||
raw=snapshot.contents,
|
||||
snapshot=snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _source_precondition(document: LettaDocument) -> FilePrecondition:
|
||||
return FilePrecondition(
|
||||
document.file_path,
|
||||
letta_document_label(document),
|
||||
document.snapshot,
|
||||
MAX_SOURCE_BYTES,
|
||||
)
|
||||
|
||||
|
||||
def _deduplicate_preconditions(
|
||||
values: list[FilePrecondition],
|
||||
) -> Tuple[FilePrecondition, ...]:
|
||||
result: Dict[str, FilePrecondition] = {}
|
||||
for value in values:
|
||||
result.setdefault(_comparison_path(value.file_path), value)
|
||||
return tuple(result.values())
|
||||
|
||||
|
||||
def _effective_disable(
|
||||
global_settings: LettaDocument,
|
||||
project: LettaDocument,
|
||||
project_local: LettaDocument,
|
||||
project_active: bool,
|
||||
) -> LettaDisableControl:
|
||||
if global_settings.hooks.get("disabled") is False:
|
||||
return LettaDisableControl(False, global_settings)
|
||||
if global_settings.hooks.get("disabled") is True:
|
||||
return LettaDisableControl(True, global_settings)
|
||||
if project_active and project.hooks.get("disabled") is True:
|
||||
return LettaDisableControl(True, project)
|
||||
if project_local.hooks.get("disabled") is True:
|
||||
return LettaDisableControl(True, project_local)
|
||||
return LettaDisableControl(False, None)
|
||||
|
||||
|
||||
def read_letta_sources() -> LettaSources:
|
||||
home_directory = _home_directory()
|
||||
workspace = os.path.abspath(os.getcwd())
|
||||
global_directory = os.path.join(home_directory, ".letta")
|
||||
project_directory = os.path.join(workspace, ".letta")
|
||||
physical_directory_exists(home_directory, "Letta Code home directory")
|
||||
physical_directory_exists(
|
||||
global_directory, "Letta Code global configuration directory"
|
||||
)
|
||||
if not same_letta_path(project_directory, global_directory):
|
||||
physical_directory_exists(
|
||||
project_directory, "Letta Code project configuration directory"
|
||||
)
|
||||
global_path = os.path.join(global_directory, "settings.json")
|
||||
project_path = os.path.join(project_directory, "settings.json")
|
||||
local_path = os.path.join(project_directory, "settings.local.json")
|
||||
project_active = _comparison_path(_canonical_path(workspace)) != _comparison_path(
|
||||
_canonical_path(home_directory)
|
||||
)
|
||||
global_settings = _read_document("global", global_path)
|
||||
project = (
|
||||
_read_document("project", project_path)
|
||||
if project_active
|
||||
else create_letta_document("project", project_path)
|
||||
)
|
||||
project_local = _read_document("project-local", local_path)
|
||||
preconditions = [_source_precondition(global_settings)]
|
||||
if project_active:
|
||||
preconditions.append(_source_precondition(project))
|
||||
preconditions.append(_source_precondition(project_local))
|
||||
return LettaSources(
|
||||
home_directory,
|
||||
global_settings,
|
||||
project,
|
||||
project_local,
|
||||
project_active,
|
||||
_effective_disable(
|
||||
global_settings, project, project_local, project_active
|
||||
),
|
||||
_deduplicate_preconditions(preconditions),
|
||||
)
|
||||
|
||||
|
||||
def require_letta_hooks_enabled(sources: LettaSources) -> None:
|
||||
if not sources.disable_control.disabled:
|
||||
return
|
||||
source = sources.disable_control.source
|
||||
location = (
|
||||
f"{letta_document_label(source)} at {source.file_path}"
|
||||
if source is not None
|
||||
else "effective settings"
|
||||
)
|
||||
raise ValueError(
|
||||
f"Letta Code hooks are disabled by hooks.disabled in {location}"
|
||||
)
|
||||
@@ -68,7 +68,7 @@ SUPPORTED_AGENTS: Dict[str, Dict[str, str]] = {
|
||||
},
|
||||
"letta": {
|
||||
"name": "Letta Code",
|
||||
"hook_event": "PostToolUse",
|
||||
"hook_event": "PreToolUse/PostToolUse/PostToolUseFailure",
|
||||
"config_path": "~/.letta/settings.json",
|
||||
},
|
||||
"opencode": {
|
||||
|
||||
Reference in new issue
Block a user