Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 112 additions & 4 deletions libs/code/deepagents_code/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3043,11 +3043,11 @@ def __init__(

self._register_custom_themes()
self._hook_trust: WorkspaceTrust | None = hook_trust
"""Project-hook trust policy, forwarded verbatim to `HooksManager`.
"""Project-hook trust policy used before and during manager construction.

Carried rather than applied: session state — and therefore the hooks
coordinator that owns and resolves this policy — cannot be built until
after construction. The app never inspects it.
Session state may be built concurrently with a launch-time cwd switch, so
in-session trust decisions replace this value as well as the live manager's
policy. Whichever path finishes construction then observes the same policy.
"""

self.theme = _load_theme_preference()
Expand Down Expand Up @@ -4723,6 +4723,107 @@ async def _reload_hooks(

await self._hooks.reload(cwd=Path(self._cwd), plugins=plugins)

def _current_hook_trust(self) -> WorkspaceTrust:
"""Return the policy owned by the live or not-yet-built hooks manager."""
from deepagents_code.hooks.trust import WorkspaceTrust

if self._session_state is not None:
return self._session_state.hooks.trust
if self._hook_trust is not None:
return self._hook_trust
if self._detached_hooks is not None:
return self._detached_hooks.trust
return WorkspaceTrust.none()

async def _reload_hooks_with_trust(self, trust: WorkspaceTrust) -> None:
"""Apply a replacement trust policy and reload the current hooks manager."""
self._hook_trust = trust
manager = self._hooks
manager.trust = trust
await self._reload_hooks()

async def _wait_for_hook_trust_prompt_refresh(self) -> None:
"""Let the cwd-switch modal unwind before mounting the trust prompt."""
if not self.is_running:
return
refreshed = asyncio.Event()
if not self.call_after_refresh(refreshed.set):
return
await refreshed.wait()

async def _retarget_hooks_after_cwd_switch(self) -> None:
"""Reload hooks and gate project commands after a successful cwd switch."""
from deepagents_code._env_vars import EXPERIMENTAL, is_env_truthy

if not is_env_truthy(EXPERIMENTAL):
return

from deepagents_code.hooks.loading import project_hooks_path
from deepagents_code.hooks.trust import (
project_root_for,
trust_project_hooks,
)
from deepagents_code.tui.widgets.hook_trust import HookTrustScreen

trust = self._current_hook_trust()
try:
root = await asyncio.to_thread(project_root_for, Path(self._cwd))
config_path = project_hooks_path(root)
has_project_hooks = await asyncio.to_thread(config_path.is_file)
except (OSError, ValueError):
logger.warning(
"Could not inspect project hooks after cwd switch",
exc_info=True,
)
await self._reload_hooks_with_trust(trust)
return

if not has_project_hooks or await asyncio.to_thread(trust.allows, root):
await self._reload_hooks_with_trust(trust)
return

trust = await asyncio.to_thread(trust.without_session_grant, root)
if not trust.consult_store:
await self._reload_hooks_with_trust(trust)
return
prompt_grant = await asyncio.to_thread(trust.with_session_grant, root)
await self._wait_for_hook_trust_prompt_refresh()

try:
choice = await self._push_screen_wait(
HookTrustScreen(
project_root=str(root),
config_path=str(config_path),
)
)
except Exception:
logger.warning(
"Project hooks trust prompt failed after cwd switch",
exc_info=True,
)
self.notify(
"Project hooks were not loaded because the trust prompt failed.",
severity="warning",
markup=False,
)
choice = None

if choice in {"allow_once", "always_allow"}:
trust = prompt_grant
if choice == "always_allow" and not await asyncio.to_thread(
trust_project_hooks,
root,
store_path=trust.store_path,
):
self.notify(
"Approved for this session, but the decision could not be "
"saved — you may be asked again next time.",
severity="warning",
markup=False,
)

await self._reload_hooks_with_trust(trust)

async def _run_session_start_hook(self, cause: SessionStartCause) -> bool:
"""Run `SessionStart`, surfacing a stop as a chat message.

Expand Down Expand Up @@ -24508,9 +24609,12 @@ async def _offer_thread_cwd_switch(
"on the current thread.",
)
)
return outcome
await self._retarget_hooks_after_cwd_switch()
return outcome
self._preserve_launch_relative_server_paths(Path(self._cwd))
self._switch_process_cwd(target)
await self._retarget_hooks_after_cwd_switch()
Comment thread
johannes117 marked this conversation as resolved.
Resolved
return "continue"

self.notify(
Expand Down Expand Up @@ -24559,6 +24663,8 @@ async def _restore_cwd_after_failed_thread_switch(self, previous_cwd: Path) -> N
"rollback",
previous_cwd,
)
return
await self._reload_hooks()
return

try:
Expand All @@ -24577,6 +24683,8 @@ async def _restore_cwd_after_failed_thread_switch(self, previous_cwd: Path) -> N
timeout=15,
markup=False,
)
return
await self._reload_hooks()

async def _resume_thread(self, thread_id: str) -> None:
"""Resume a previously saved thread.
Expand Down
105 changes: 85 additions & 20 deletions libs/code/deepagents_code/hooks/trust.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

from __future__ import annotations

import hashlib
import json
import logging
import os
import tempfile
import threading
from contextlib import contextmanager, suppress
from dataclasses import dataclass
from dataclasses import dataclass, replace
from datetime import UTC, datetime
from pathlib import Path
from typing import TYPE_CHECKING, Literal
Expand Down Expand Up @@ -337,6 +338,21 @@ def project_root_for(cwd: Path | str) -> Path:
return context.project_root or context.user_cwd


def _project_hooks_fingerprint(project_root: Path) -> str | None:
"""Return a content fingerprint for a workspace's project hooks file."""
from deepagents_code.hooks.loading import project_hooks_path

try:
content = project_hooks_path(project_root).read_bytes()
except OSError:
logger.warning(
"Could not fingerprint project hooks for session trust",
exc_info=True,
)
return None
return hashlib.sha256(content).hexdigest()


@dataclass(frozen=True, slots=True)
class WorkspaceTrust:
"""Decides whether project-scoped hooks may run in a given directory.
Expand Down Expand Up @@ -368,6 +384,9 @@ class WorkspaceTrust:
store_path: Path | None = None
"""Alternate trust store path for tests."""

session_grant_fingerprints: frozenset[tuple[str, str]] = frozenset()
"""Project-hooks content fingerprints captured with session grants."""

@classmethod
def none(cls) -> WorkspaceTrust:
"""Return a policy that trusts no workspace.
Expand Down Expand Up @@ -397,10 +416,8 @@ def for_session(
A policy that grants `cwd`'s workspace root for this session and
defers to the persisted store everywhere else.
"""
return cls(
session_grants=cls._grants_for(cwd) if granted else frozenset(),
store_path=store_path,
)
policy = cls(store_path=store_path)
return policy.with_session_grant(cwd) if granted else policy

@classmethod
def explicit_only(
Expand All @@ -426,22 +443,68 @@ def explicit_only(
A policy that allows `cwd`'s workspace root only when `granted`, and
allows nothing otherwise.
"""
return cls(
session_grants=cls._grants_for(cwd) if granted else frozenset(),
consult_store=False,
store_path=store_path,
)
policy = cls(consult_store=False, store_path=store_path)
return policy.with_session_grant(cwd) if granted else policy

@staticmethod
def _grants_for(cwd: Path | str) -> frozenset[str]:
def with_session_grant(self, cwd: Path | str) -> WorkspaceTrust:
"""Return a policy with a content-bound session grant for `cwd`.

Args:
cwd: Directory whose workspace should be granted.

Returns:
A replacement policy preserving persisted-store posture. Fingerprint
failures leave the workspace ungranted.
"""
try:
return frozenset({_project_key(project_root_for(cwd))})
root = project_root_for(cwd)
except (OSError, ValueError):
logger.warning(
"Could not resolve workspace root for session hook trust",
exc_info=True,
)
return frozenset()
return self
key = _project_key(root)
fingerprints = dict(self.session_grant_fingerprints)
fingerprint = _project_hooks_fingerprint(root)
if fingerprint is None:
fingerprints.pop(key, None)
return replace(
self,
session_grants=self.session_grants - {key},
session_grant_fingerprints=frozenset(fingerprints.items()),
)
fingerprints[key] = fingerprint
return replace(
self,
session_grants=self.session_grants | {key},
session_grant_fingerprints=frozenset(fingerprints.items()),
)

def without_session_grant(self, cwd: Path | str) -> WorkspaceTrust:
"""Return a policy without any session grant for `cwd`.

Args:
cwd: Directory whose workspace grant should be removed.

Returns:
A replacement policy preserving persisted-store posture.
"""
try:
key = _project_key(project_root_for(cwd))
except (OSError, ValueError):
logger.warning(
"Could not resolve workspace root while revoking session hook trust",
exc_info=True,
)
return self
fingerprints = dict(self.session_grant_fingerprints)
fingerprints.pop(key, None)
return replace(
self,
session_grants=self.session_grants - {key},
session_grant_fingerprints=frozenset(fingerprints.items()),
)

def allows(self, cwd: Path | str) -> bool:
"""Return whether project hooks may run for a working directory.
Expand All @@ -450,21 +513,23 @@ def allows(self, cwd: Path | str) -> bool:
cwd: Directory to resolve trust for.

Returns:
`True` when the enclosing workspace root was granted for this
session, or is recorded in the trust store and `consult_store` is
set. Unresolvable directories fail closed.
`True` when the enclosing workspace root has an unchanged session
grant, or is recorded in the trust store and `consult_store` is set.
Unresolvable directories fail closed.
"""
try:
root = project_root_for(cwd)
except (OSError, ValueError):
# The raised exception carries the offending path; don't restate it.
logger.warning(
"Could not resolve workspace root; treating project hooks as untrusted",
exc_info=True,
)
return False
if _project_key(root) in self.session_grants:
return True
key = _project_key(root)
if key in self.session_grants:
granted_fingerprint = dict(self.session_grant_fingerprints).get(key)
if granted_fingerprint == _project_hooks_fingerprint(root):
return True
Comment thread
johannes117 marked this conversation as resolved.
Resolved
if not self.consult_store:
return False
return is_project_hooks_trusted(root, store_path=self.store_path)
Loading