From 1db711da511937c95936c33a1fec494b2c9a317f Mon Sep 17 00:00:00 2001 From: Johannes du Plessis Date: Mon, 20 Jul 2026 14:03:41 -0700 Subject: [PATCH 1/6] feat(code): add typed hooks data models Establish domain, wire, configuration, and transport contracts so hook execution can be implemented against validated event-specific types. Co-authored-by: Cursor --- libs/code/deepagents_code/hooks/__init__.py | 24 ++ .../{hooks.py => hooks/legacy.py} | 2 +- .../deepagents_code/hooks/models/__init__.py | 1 + .../deepagents_code/hooks/models/adapters.py | 24 ++ .../deepagents_code/hooks/models/config.py | 40 ++ .../deepagents_code/hooks/models/domain.py | 337 +++++++++++++++ .../deepagents_code/hooks/models/transport.py | 40 ++ .../code/deepagents_code/hooks/models/wire.py | 390 ++++++++++++++++++ libs/code/deepagents_code/json_types.py | 7 +- libs/code/tests/unit_tests/hooks/__init__.py | 1 + .../tests/unit_tests/hooks/models/__init__.py | 1 + .../unit_tests/hooks/models/test_models.py | 374 +++++++++++++++++ libs/code/tests/unit_tests/test_hooks.py | 2 +- libs/code/tests/unit_tests/test_json_types.py | 26 +- 14 files changed, 1264 insertions(+), 5 deletions(-) create mode 100644 libs/code/deepagents_code/hooks/__init__.py rename libs/code/deepagents_code/{hooks.py => hooks/legacy.py} (99%) create mode 100644 libs/code/deepagents_code/hooks/models/__init__.py create mode 100644 libs/code/deepagents_code/hooks/models/adapters.py create mode 100644 libs/code/deepagents_code/hooks/models/config.py create mode 100644 libs/code/deepagents_code/hooks/models/domain.py create mode 100644 libs/code/deepagents_code/hooks/models/transport.py create mode 100644 libs/code/deepagents_code/hooks/models/wire.py create mode 100644 libs/code/tests/unit_tests/hooks/__init__.py create mode 100644 libs/code/tests/unit_tests/hooks/models/__init__.py create mode 100644 libs/code/tests/unit_tests/hooks/models/test_models.py diff --git a/libs/code/deepagents_code/hooks/__init__.py b/libs/code/deepagents_code/hooks/__init__.py new file mode 100644 index 00000000000..502ea93819e --- /dev/null +++ b/libs/code/deepagents_code/hooks/__init__.py @@ -0,0 +1,24 @@ +"""Hook contracts and compatibility dispatch.""" + +from deepagents_code.hooks.legacy import ( + HOOK_SUBPROCESS_TIMEOUT, + HOOK_TOOL_OUTPUT_LIMIT, + _background_tasks, + _dispatch_hook_sync as _dispatch_hook_sync, + _load_hooks as _load_hooks, + dispatch_hook, + dispatch_hook_fire_and_forget, + drain_pending_hooks, + has_pending_hooks, + subprocess as subprocess, +) + +__all__ = [ + "HOOK_SUBPROCESS_TIMEOUT", + "HOOK_TOOL_OUTPUT_LIMIT", + "_background_tasks", + "dispatch_hook", + "dispatch_hook_fire_and_forget", + "drain_pending_hooks", + "has_pending_hooks", +] diff --git a/libs/code/deepagents_code/hooks.py b/libs/code/deepagents_code/hooks/legacy.py similarity index 99% rename from libs/code/deepagents_code/hooks.py rename to libs/code/deepagents_code/hooks/legacy.py index df6c40ecbe7..027e612c43c 100644 --- a/libs/code/deepagents_code/hooks.py +++ b/libs/code/deepagents_code/hooks/legacy.py @@ -79,7 +79,7 @@ if TYPE_CHECKING: from collections.abc import Mapping -logger = logging.getLogger(__name__) +logger = logging.getLogger("deepagents_code.hooks") HOOK_TOOL_OUTPUT_LIMIT = 2000 """Max characters of `tool_output` included in `tool.result` hook payloads. diff --git a/libs/code/deepagents_code/hooks/models/__init__.py b/libs/code/deepagents_code/hooks/models/__init__.py new file mode 100644 index 00000000000..c2c16598eaf --- /dev/null +++ b/libs/code/deepagents_code/hooks/models/__init__.py @@ -0,0 +1 @@ +"""Typed contracts for the hooks system.""" diff --git a/libs/code/deepagents_code/hooks/models/adapters.py b/libs/code/deepagents_code/hooks/models/adapters.py new file mode 100644 index 00000000000..d12d5565c75 --- /dev/null +++ b/libs/code/deepagents_code/hooks/models/adapters.py @@ -0,0 +1,24 @@ +"""Cached runtime validators for hook model boundaries.""" + +from pydantic import TypeAdapter + +from deepagents_code.hooks.models.config import HooksConfig +from deepagents_code.hooks.models.domain import ( + HookDecision, + HookDomainEvent, + HookInvocation, +) +from deepagents_code.hooks.models.transport import ( + HookInvocationRequest, + HookInvocationResponse, +) +from deepagents_code.hooks.models.wire import HookWireInput, HookWireOutput + +HOOK_DOMAIN_EVENT_ADAPTER = TypeAdapter(HookDomainEvent) +HOOK_INVOCATION_ADAPTER = TypeAdapter(HookInvocation) +HOOK_DECISION_ADAPTER = TypeAdapter(HookDecision) +HOOK_WIRE_INPUT_ADAPTER = TypeAdapter(HookWireInput) +HOOK_WIRE_OUTPUT_ADAPTER = TypeAdapter(HookWireOutput) +HOOKS_CONFIG_ADAPTER = TypeAdapter(HooksConfig) +HOOK_INVOCATION_REQUEST_ADAPTER = TypeAdapter(HookInvocationRequest) +HOOK_INVOCATION_RESPONSE_ADAPTER = TypeAdapter(HookInvocationResponse) diff --git a/libs/code/deepagents_code/hooks/models/config.py b/libs/code/deepagents_code/hooks/models/config.py new file mode 100644 index 00000000000..edb576e463a --- /dev/null +++ b/libs/code/deepagents_code/hooks/models/config.py @@ -0,0 +1,40 @@ +"""Validated hook configuration models.""" + +from __future__ import annotations + +from typing import Literal, TypeAlias + +from pydantic import BaseModel, ConfigDict, Field + +from deepagents_code.hooks.models.domain import ( # noqa: TC001 - Pydantic runtime annotation. + HookEvent, +) + + +class _ConfigModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class CommandHandlerSpec(_ConfigModel): + """Configuration for a synchronous command hook.""" + + type: Literal["command"] + command: str + timeout: float | None = None + status_message: str | None = Field(default=None, alias="statusMessage") + + +HandlerSpec: TypeAlias = CommandHandlerSpec + + +class MatcherGroup(_ConfigModel): + """A matcher and its ordered hook handlers.""" + + matcher: str | None = None + hooks: list[HandlerSpec] + + +class HooksConfig(_ConfigModel): + """Top-level configuration grouped by hook event.""" + + hooks: dict[HookEvent, list[MatcherGroup]] diff --git a/libs/code/deepagents_code/hooks/models/domain.py b/libs/code/deepagents_code/hooks/models/domain.py new file mode 100644 index 00000000000..a8f304b251d --- /dev/null +++ b/libs/code/deepagents_code/hooks/models/domain.py @@ -0,0 +1,337 @@ +"""Domain models for hook lifecycle invocations and decisions.""" + +from __future__ import annotations + +from enum import StrEnum +from pathlib import ( + Path, # noqa: TC003 - Pydantic resolves model annotations at runtime. +) +from typing import Annotated, Literal, TypeAlias +from uuid import UUID # noqa: TC003 - Pydantic resolves model annotations at runtime. + +from langchain_core.messages import ( # noqa: TC002 - Pydantic runtime annotation. + ToolMessage, +) +from langgraph.types import Command # noqa: TC002 - Pydantic runtime annotation. +from pydantic import BaseModel, ConfigDict, Field + +from deepagents_code.approval_mode import ( # noqa: TC001 - Pydantic runtime annotation. + ApprovalMode, +) +from deepagents_code.json_types import ( # noqa: TC001 - Pydantic runtime annotation. + JsonObject, +) + + +class _DomainModel(BaseModel): + model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True) + + +class HookEvent(StrEnum): + """Supported hook lifecycle events.""" + + SESSION_START = "SessionStart" + SESSION_END = "SessionEnd" + PERMISSION_REQUEST = "PermissionRequest" + NOTIFICATION = "Notification" + PRE_TOOL_USE = "PreToolUse" + POST_TOOL_USE = "PostToolUse" + STOP = "Stop" + SUBAGENT_START = "SubagentStart" + SUBAGENT_STOP = "SubagentStop" + + +class HookOwner(StrEnum): + """Process responsible for originating an event.""" + + CLIENT = "client" + SERVER = "server" + + +class SessionStartCause(StrEnum): + """Reason a session-start event occurred.""" + + STARTUP = "startup" + RESUME = "resume" + CLEAR = "clear" + COMPACT = "compact" + + +class SessionEndCause(StrEnum): + """Reason a session-end event occurred.""" + + CLEAR = "clear" + RESUME = "resume" + LOGOUT = "logout" + PROMPT_INPUT_EXIT = "prompt_input_exit" + BYPASS_PERMISSIONS_DISABLED = "bypass_permissions_disabled" + OTHER = "other" + + +EffortLevel: TypeAlias = Literal["low", "medium", "high", "xhigh", "max"] + + +class ToolCallData(_DomainModel): + """Native tool-call data used by hook lifecycle owners.""" + + id: str + name: str + args: JsonObject + + +class AgentIdentity(_DomainModel): + """Resolved subagent identity.""" + + id: str + name: str + + +class DcodeNotification(_DomainModel): + """A notification emitted by a dcode lifecycle owner.""" + + type: str + message: str + title: str | None = None + + +class BackgroundTaskSnapshot(_DomainModel): + """Background task state captured for a hook invocation.""" + + id: str + type: str + status: str + description: str + command: str | None = None + agent_type: str | None = None + server: str | None = None + tool: str | None = None + name: str | None = None + + +class SessionCronSnapshot(_DomainModel): + """Scheduled session prompt captured for a hook invocation.""" + + id: str + schedule: str + recurring: bool + prompt: str + + +class HookContext(_DomainModel): + """Context shared by every domain hook event.""" + + thread_id: str + cwd: Path + prompt_id: UUID | None = None + approval_mode: ApprovalMode + effort: EffortLevel | None = None + agent: AgentIdentity | None = None + transcript_revision: str | None = None + + +class SessionStartEvent(_DomainModel): + """Domain payload for `SessionStart`.""" + + event: Literal[HookEvent.SESSION_START] + cause: SessionStartCause + model: str | None = None + + +class SessionEndEvent(_DomainModel): + """Domain payload for `SessionEnd`.""" + + event: Literal[HookEvent.SESSION_END] + cause: SessionEndCause + + +class PermissionRequestEvent(_DomainModel): + """Domain payload for `PermissionRequest`.""" + + event: Literal[HookEvent.PERMISSION_REQUEST] + call: ToolCallData + + +class NotificationEvent(_DomainModel): + """Domain payload for `Notification`.""" + + event: Literal[HookEvent.NOTIFICATION] + notification: DcodeNotification + + +class PreToolUseEvent(_DomainModel): + """Domain payload for `PreToolUse`.""" + + event: Literal[HookEvent.PRE_TOOL_USE] + call: ToolCallData + + +class PostToolUseEvent(_DomainModel): + """Domain payload for `PostToolUse`.""" + + event: Literal[HookEvent.POST_TOOL_USE] + call: ToolCallData + result: ToolMessage | Command[str] + duration_ms: int | None = None + + +class StopEvent(_DomainModel): + """Domain payload for `Stop`.""" + + event: Literal[HookEvent.STOP] + continuation_count: int + last_assistant_message: str + background_tasks: list[BackgroundTaskSnapshot] = Field(default_factory=list) + session_crons: list[SessionCronSnapshot] = Field(default_factory=list) + + +class SubagentStartEvent(_DomainModel): + """Domain payload for `SubagentStart`.""" + + event: Literal[HookEvent.SUBAGENT_START] + agent: AgentIdentity + + +class SubagentStopEvent(_DomainModel): + """Domain payload for `SubagentStop`.""" + + event: Literal[HookEvent.SUBAGENT_STOP] + agent: AgentIdentity + continuation_count: int + last_assistant_message: str + transcript_revision: str | None = None + background_tasks: list[BackgroundTaskSnapshot] = Field(default_factory=list) + session_crons: list[SessionCronSnapshot] = Field(default_factory=list) + + +HookDomainEvent: TypeAlias = Annotated[ + SessionStartEvent + | SessionEndEvent + | PermissionRequestEvent + | NotificationEvent + | PreToolUseEvent + | PostToolUseEvent + | StopEvent + | SubagentStartEvent + | SubagentStopEvent, + Field(discriminator="event"), +] + + +class HookInvocation(_DomainModel): + """A domain hook event with its invocation context.""" + + context: HookContext + event: HookDomainEvent + + +class HookDiagnostic(_DomainModel): + """Structured diagnostic produced while processing a hook.""" + + code: str + severity: Literal["debug", "warning", "error"] + message: str + handler_id: str | None = None + field: str | None = None + + +class PermissionEffect(_DomainModel): + """Normalized permission result from hook processing.""" + + behavior: Literal["allow", "deny", "ask", "none"] + reason: str | None = None + interrupt: bool = False + + +class BaseHookDecision(_DomainModel): + """Fields common to every event-specific hook decision.""" + + continue_processing: bool = True + stop_reason: str | None = None + user_notices: list[str] = Field(default_factory=list) + terminal_sequences: list[str] = Field(default_factory=list) + diagnostics: list[HookDiagnostic] = Field(default_factory=list) + + +class SessionStartDecision(BaseHookDecision): + """Decision returned for `SessionStart`.""" + + event: Literal[HookEvent.SESSION_START] + context: list[str] = Field(default_factory=list) + + +class SessionEndDecision(BaseHookDecision): + """Decision returned for `SessionEnd`.""" + + event: Literal[HookEvent.SESSION_END] + + +class PermissionRequestDecision(BaseHookDecision): + """Decision returned for `PermissionRequest`.""" + + event: Literal[HookEvent.PERMISSION_REQUEST] + permission: PermissionEffect + + +class NotificationDecision(BaseHookDecision): + """Decision returned for `Notification`.""" + + event: Literal[HookEvent.NOTIFICATION] + + +class PreToolUseDecision(BaseHookDecision): + """Decision returned for `PreToolUse`.""" + + event: Literal[HookEvent.PRE_TOOL_USE] + permission: PermissionEffect + context: list[str] = Field(default_factory=list) + + +class PostToolUseDecision(BaseHookDecision): + """Decision returned for `PostToolUse`.""" + + event: Literal[HookEvent.POST_TOOL_USE] + feedback: list[str] = Field(default_factory=list) + context: list[str] = Field(default_factory=list) + + +class StopDecision(BaseHookDecision): + """Decision returned for `Stop`.""" + + event: Literal[HookEvent.STOP] + continue_loop: bool + feedback: list[str] = Field(default_factory=list) + + +class SubagentStartDecision(BaseHookDecision): + """Decision returned for `SubagentStart`.""" + + event: Literal[HookEvent.SUBAGENT_START] + context: list[str] = Field(default_factory=list) + + +class SubagentStopDecision(BaseHookDecision): + """Decision returned for `SubagentStop`.""" + + event: Literal[HookEvent.SUBAGENT_STOP] + context: list[str] = Field(default_factory=list) + + +HookDecision: TypeAlias = Annotated[ + SessionStartDecision + | SessionEndDecision + | PermissionRequestDecision + | NotificationDecision + | PreToolUseDecision + | PostToolUseDecision + | StopDecision + | SubagentStartDecision + | SubagentStopDecision, + Field(discriminator="event"), +] + + +class HookEffect(_DomainModel): + """Normalized effect produced by one hook handler.""" + + handler_id: str + decision: HookDecision diff --git a/libs/code/deepagents_code/hooks/models/transport.py b/libs/code/deepagents_code/hooks/models/transport.py new file mode 100644 index 00000000000..096527f3694 --- /dev/null +++ b/libs/code/deepagents_code/hooks/models/transport.py @@ -0,0 +1,40 @@ +"""Versioned hook invocation transport models.""" + +from __future__ import annotations + +from datetime import ( # noqa: TC003 - Pydantic resolves model annotations at runtime. + datetime, +) +from typing import Literal +from uuid import UUID # noqa: TC003 - Pydantic resolves model annotations at runtime. + +from pydantic import BaseModel, ConfigDict + +from deepagents_code.hooks.models.domain import ( # noqa: TC001 - Pydantic runtime annotation. + HookDecision, + HookInvocation, +) + + +class _TransportModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class HookInvocationRequest(_TransportModel): + """Request sent for a server-owned hook invocation.""" + + protocol_version: Literal[1] + invocation_id: UUID + snapshot_id: str + run_id: str + invocation: HookInvocation + deadline: datetime + + +class HookInvocationResponse(_TransportModel): + """Response returned for a server-owned hook invocation.""" + + protocol_version: Literal[1] + invocation_id: UUID + snapshot_id: str + decision: HookDecision diff --git a/libs/code/deepagents_code/hooks/models/wire.py b/libs/code/deepagents_code/hooks/models/wire.py new file mode 100644 index 00000000000..b8468c4059f --- /dev/null +++ b/libs/code/deepagents_code/hooks/models/wire.py @@ -0,0 +1,390 @@ +"""External JSON-compatible hook input and output models.""" + +from __future__ import annotations + +from enum import StrEnum +from typing import Annotated, Literal, TypeAlias +from uuid import UUID # noqa: TC003 - Pydantic resolves model annotations at runtime. + +from pydantic import BaseModel, ConfigDict, Field + +from deepagents_code.hooks.models.domain import ( # noqa: TC001 - Pydantic runtime annotation. + EffortLevel, + HookEvent, + SessionEndCause, + SessionStartCause, +) +from deepagents_code.json_types import ( # noqa: TC001 - Pydantic runtime annotation. + JsonObject, + JsonValue, +) + + +class _WireModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class WirePermissionMode(StrEnum): + """Permission modes exposed by the compatible wire protocol.""" + + DEFAULT = "default" + PLAN = "plan" + ACCEPT_EDITS = "acceptEdits" + AUTO = "auto" + DONT_ASK = "dontAsk" + BYPASS_PERMISSIONS = "bypassPermissions" + + +class WireNotificationType(StrEnum): + """Notification matcher values exposed on the wire.""" + + PERMISSION_PROMPT = "permission_prompt" + IDLE_PROMPT = "idle_prompt" + AUTH_SUCCESS = "auth_success" + ELICITATION_DIALOG = "elicitation_dialog" + ELICITATION_COMPLETE = "elicitation_complete" + ELICITATION_RESPONSE = "elicitation_response" + AGENT_NEEDS_INPUT = "agent_needs_input" + AGENT_COMPLETED = "agent_completed" + + +class Effort(_WireModel): + """Wire representation of model effort.""" + + level: EffortLevel + + +class PermissionRule(_WireModel): + """Permission rule returned by a hook.""" + + tool_name: str = Field(alias="toolName") + rule_content: str | None = Field(default=None, alias="ruleContent") + + +class PermissionDestination(StrEnum): + """Configuration scope targeted by a permission update.""" + + SESSION = "session" + LOCAL = "localSettings" + PROJECT = "projectSettings" + USER = "userSettings" + + +class AddRulesUpdate(_WireModel): + """Permission update that adds rules.""" + + type: Literal["addRules"] + rules: list[PermissionRule] + behavior: Literal["allow", "deny", "ask"] + destination: PermissionDestination + + +class ReplaceRulesUpdate(_WireModel): + """Permission update that replaces rules.""" + + type: Literal["replaceRules"] + rules: list[PermissionRule] + behavior: Literal["allow", "deny", "ask"] + destination: PermissionDestination + + +class RemoveRulesUpdate(_WireModel): + """Permission update that removes rules.""" + + type: Literal["removeRules"] + rules: list[PermissionRule] + behavior: Literal["allow", "deny", "ask"] + destination: PermissionDestination + + +class SetModeUpdate(_WireModel): + """Permission update that changes the active mode.""" + + type: Literal["setMode"] + mode: WirePermissionMode | Literal["manual"] + destination: PermissionDestination + + +class AddDirectoriesUpdate(_WireModel): + """Permission update that adds allowed directories.""" + + type: Literal["addDirectories"] + directories: list[str] + destination: PermissionDestination + + +class RemoveDirectoriesUpdate(_WireModel): + """Permission update that removes allowed directories.""" + + type: Literal["removeDirectories"] + directories: list[str] + destination: PermissionDestination + + +PermissionUpdate: TypeAlias = Annotated[ + AddRulesUpdate + | ReplaceRulesUpdate + | RemoveRulesUpdate + | SetModeUpdate + | AddDirectoriesUpdate + | RemoveDirectoriesUpdate, + Field(discriminator="type"), +] + + +class BackgroundTaskWire(_WireModel): + """Background task snapshot exposed to hook handlers.""" + + id: str + type: str + status: str + description: str + command: str | None = None + agent_type: str | None = None + server: str | None = None + tool: str | None = None + name: str | None = None + + +class SessionCronWire(_WireModel): + """Scheduled session prompt exposed to hook handlers.""" + + id: str + schedule: str + recurring: bool + prompt: str + + +class BaseHookWireInput(_WireModel): + """Fields common to every hook input.""" + + session_id: str + transcript_path: str + cwd: str + hook_event_name: HookEvent + prompt_id: UUID | None = None + permission_mode: WirePermissionMode | None = None + effort: Effort | None = None + agent_id: str | None = None + agent_type: str | None = None + + +class SessionStartWireInput(BaseHookWireInput): + """Wire input for `SessionStart`.""" + + hook_event_name: Literal[HookEvent.SESSION_START] + source: SessionStartCause + model: str | None = None + session_title: str | None = None + + +class SessionEndWireInput(BaseHookWireInput): + """Wire input for `SessionEnd`.""" + + hook_event_name: Literal[HookEvent.SESSION_END] + reason: SessionEndCause + + +class PermissionRequestWireInput(BaseHookWireInput): + """Wire input for `PermissionRequest`.""" + + hook_event_name: Literal[HookEvent.PERMISSION_REQUEST] + tool_name: str + tool_input: JsonObject + permission_suggestions: list[PermissionUpdate] = Field(default_factory=list) + + +class NotificationWireInput(BaseHookWireInput): + """Wire input for `Notification`.""" + + hook_event_name: Literal[HookEvent.NOTIFICATION] + message: str + notification_type: WireNotificationType + title: str | None = None + + +class PreToolUseWireInput(BaseHookWireInput): + """Wire input for `PreToolUse`.""" + + hook_event_name: Literal[HookEvent.PRE_TOOL_USE] + tool_name: str + tool_input: JsonObject + tool_use_id: str + + +class PostToolUseWireInput(BaseHookWireInput): + """Wire input for `PostToolUse`.""" + + hook_event_name: Literal[HookEvent.POST_TOOL_USE] + tool_name: str + tool_input: JsonObject + tool_response: JsonValue + tool_use_id: str + duration_ms: int | None = None + + +class StopWireInput(BaseHookWireInput): + """Wire input for `Stop`.""" + + hook_event_name: Literal[HookEvent.STOP] + stop_hook_active: bool + last_assistant_message: str + background_tasks: list[BackgroundTaskWire] = Field(default_factory=list) + session_crons: list[SessionCronWire] = Field(default_factory=list) + + +class SubagentStartWireInput(BaseHookWireInput): + """Wire input for `SubagentStart`.""" + + hook_event_name: Literal[HookEvent.SUBAGENT_START] + agent_id: str + agent_type: str + + +class SubagentStopWireInput(BaseHookWireInput): + """Wire input for `SubagentStop`.""" + + hook_event_name: Literal[HookEvent.SUBAGENT_STOP] + stop_hook_active: bool + agent_id: str + agent_type: str + agent_transcript_path: str + last_assistant_message: str + background_tasks: list[BackgroundTaskWire] = Field(default_factory=list) + session_crons: list[SessionCronWire] = Field(default_factory=list) + + +HookWireInput: TypeAlias = Annotated[ + SessionStartWireInput + | SessionEndWireInput + | PermissionRequestWireInput + | NotificationWireInput + | PreToolUseWireInput + | PostToolUseWireInput + | StopWireInput + | SubagentStartWireInput + | SubagentStopWireInput, + Field(discriminator="hook_event_name"), +] + + +class SessionStartSpecificOutput(_WireModel): + """Event-specific output for `SessionStart`.""" + + hook_event_name: Literal["SessionStart"] = Field(alias="hookEventName") + additional_context: str | None = Field(default=None, alias="additionalContext") + initial_user_message: str | None = Field(default=None, alias="initialUserMessage") + session_title: str | None = Field(default=None, alias="sessionTitle") + watch_paths: list[str] = Field(default_factory=list, alias="watchPaths") + reload_skills: bool = Field(default=False, alias="reloadSkills") + + +class PreToolUseSpecificOutput(_WireModel): + """Event-specific output for `PreToolUse`.""" + + hook_event_name: Literal["PreToolUse"] = Field(alias="hookEventName") + permission_decision: Literal["allow", "deny", "ask", "defer"] | None = Field( + default=None, + alias="permissionDecision", + ) + permission_decision_reason: str | None = Field( + default=None, + alias="permissionDecisionReason", + ) + updated_input: JsonObject | None = Field(default=None, alias="updatedInput") + additional_context: str | None = Field(default=None, alias="additionalContext") + + +class PermissionAllow(_WireModel): + """Permission-request output that allows a tool call.""" + + behavior: Literal["allow"] + updated_input: JsonObject | None = Field(default=None, alias="updatedInput") + updated_permissions: list[PermissionUpdate] = Field( + default_factory=list, + alias="updatedPermissions", + ) + + +class PermissionDeny(_WireModel): + """Permission-request output that denies a tool call.""" + + behavior: Literal["deny"] + message: str | None = None + interrupt: bool = False + + +class PermissionRequestSpecificOutput(_WireModel): + """Event-specific output for `PermissionRequest`.""" + + hook_event_name: Literal["PermissionRequest"] = Field(alias="hookEventName") + decision: Annotated[ + PermissionAllow | PermissionDeny, + Field(discriminator="behavior"), + ] + + +class PostToolUseSpecificOutput(_WireModel): + """Event-specific output for `PostToolUse`.""" + + hook_event_name: Literal["PostToolUse"] = Field(alias="hookEventName") + additional_context: str | None = Field(default=None, alias="additionalContext") + updated_tool_output: JsonValue = Field( + default=None, + alias="updatedToolOutput", + ) + updated_mcp_tool_output: JsonValue = Field( + default=None, + alias="updatedMCPToolOutput", + ) + + +class StopSpecificOutput(_WireModel): + """Event-specific output for `Stop`.""" + + hook_event_name: Literal["Stop"] = Field(alias="hookEventName") + additional_context: str | None = Field(default=None, alias="additionalContext") + + +class SubagentStartSpecificOutput(_WireModel): + """Event-specific output for `SubagentStart`.""" + + hook_event_name: Literal["SubagentStart"] = Field(alias="hookEventName") + additional_context: str | None = Field(default=None, alias="additionalContext") + + +class SubagentStopSpecificOutput(_WireModel): + """Event-specific output for `SubagentStop`.""" + + hook_event_name: Literal["SubagentStop"] = Field(alias="hookEventName") + additional_context: str | None = Field(default=None, alias="additionalContext") + + +HookSpecificOutput: TypeAlias = Annotated[ + SessionStartSpecificOutput + | PreToolUseSpecificOutput + | PermissionRequestSpecificOutput + | PostToolUseSpecificOutput + | StopSpecificOutput + | SubagentStartSpecificOutput + | SubagentStopSpecificOutput, + Field(discriminator="hook_event_name"), +] + + +class HookWireOutput(BaseModel): + """Compatible hook output with retained extension fields.""" + + model_config = ConfigDict(extra="allow") + + continue_: bool = Field(default=True, alias="continue") + stop_reason: str | None = Field(default=None, alias="stopReason") + suppress_output: bool = Field(default=False, alias="suppressOutput") + system_message: str | None = Field(default=None, alias="systemMessage") + terminal_sequence: str | None = Field(default=None, alias="terminalSequence") + decision: Literal["block"] | None = None + reason: str | None = None + hook_specific_output: HookSpecificOutput | None = Field( + default=None, + alias="hookSpecificOutput", + ) diff --git a/libs/code/deepagents_code/json_types.py b/libs/code/deepagents_code/json_types.py index 13e25e4cd1a..679029a4a8d 100644 --- a/libs/code/deepagents_code/json_types.py +++ b/libs/code/deepagents_code/json_types.py @@ -2,6 +2,11 @@ from typing import TypeAlias +from pydantic import JsonValue as PydanticJsonValue, TypeAdapter + JsonScalar: TypeAlias = str | int | float | bool | None -JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"] +JsonValue: TypeAlias = PydanticJsonValue JsonObject: TypeAlias = dict[str, JsonValue] + +JSON_VALUE_ADAPTER = TypeAdapter(JsonValue) +JSON_OBJECT_ADAPTER = TypeAdapter(JsonObject) diff --git a/libs/code/tests/unit_tests/hooks/__init__.py b/libs/code/tests/unit_tests/hooks/__init__.py new file mode 100644 index 00000000000..ea1a85bf35d --- /dev/null +++ b/libs/code/tests/unit_tests/hooks/__init__.py @@ -0,0 +1 @@ +"""Hooks unit tests.""" diff --git a/libs/code/tests/unit_tests/hooks/models/__init__.py b/libs/code/tests/unit_tests/hooks/models/__init__.py new file mode 100644 index 00000000000..9d51e8d1967 --- /dev/null +++ b/libs/code/tests/unit_tests/hooks/models/__init__.py @@ -0,0 +1 @@ +"""Hooks model unit tests.""" diff --git a/libs/code/tests/unit_tests/hooks/models/test_models.py b/libs/code/tests/unit_tests/hooks/models/test_models.py new file mode 100644 index 00000000000..72321cd4411 --- /dev/null +++ b/libs/code/tests/unit_tests/hooks/models/test_models.py @@ -0,0 +1,374 @@ +"""Contract tests for hooks data models.""" + +from datetime import UTC, datetime +from pathlib import Path +from uuid import UUID, uuid4 + +import pytest +from langchain_core.messages import ToolMessage +from pydantic import ValidationError + +from deepagents_code.approval_mode import ApprovalMode +from deepagents_code.hooks.models.adapters import ( + HOOK_DECISION_ADAPTER, + HOOK_DOMAIN_EVENT_ADAPTER, + HOOK_INVOCATION_REQUEST_ADAPTER, + HOOK_INVOCATION_RESPONSE_ADAPTER, + HOOK_WIRE_INPUT_ADAPTER, + HOOK_WIRE_OUTPUT_ADAPTER, + HOOKS_CONFIG_ADAPTER, +) +from deepagents_code.hooks.models.domain import ( + HookContext, + HookEvent, + HookInvocation, + PermissionEffect, + PostToolUseEvent, + SessionStartCause, + SessionStartDecision, + SessionStartEvent, + ToolCallData, +) +from deepagents_code.hooks.models.transport import ( + HookInvocationRequest, + HookInvocationResponse, +) + +_COMMON_WIRE_INPUT = { + "session_id": "thread-1", + "transcript_path": "/tmp/transcript.jsonl", + "cwd": "/workspace", +} + +_WIRE_INPUTS = [ + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "SessionStart", + "source": "startup", + "model": "provider:model", + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "SessionEnd", + "reason": "other", + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "PermissionRequest", + "tool_name": "Bash", + "tool_input": {"command": "pwd"}, + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "Notification", + "message": "Approval required", + "notification_type": "permission_prompt", + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "PreToolUse", + "tool_name": "Write", + "tool_input": {"file_path": "notes.txt", "content": "hello"}, + "tool_use_id": "call-1", + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "PostToolUse", + "tool_name": "Bash", + "tool_input": {"command": "pwd"}, + "tool_response": {"stdout": "/workspace"}, + "tool_use_id": "call-2", + "duration_ms": 12, + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "Stop", + "stop_hook_active": False, + "last_assistant_message": "Done", + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "SubagentStart", + "agent_id": "agent-1", + "agent_type": "researcher", + }, + { + **_COMMON_WIRE_INPUT, + "hook_event_name": "SubagentStop", + "stop_hook_active": False, + "agent_id": "agent-1", + "agent_type": "researcher", + "agent_transcript_path": "/tmp/agent.jsonl", + "last_assistant_message": "Found it", + }, +] + + +@pytest.mark.parametrize("payload", _WIRE_INPUTS) +def test_wire_inputs_round_trip_with_exact_keys(payload: dict[str, object]) -> None: + parsed = HOOK_WIRE_INPUT_ADAPTER.validate_python(payload) + + assert ( + HOOK_WIRE_INPUT_ADAPTER.dump_python( + parsed, + mode="json", + by_alias=True, + exclude_none=True, + exclude_defaults=True, + ) + == payload + ) + + +def test_wire_input_rejects_unknown_fields() -> None: + payload = {**_WIRE_INPUTS[0], "unknown": True} + + with pytest.raises(ValidationError): + HOOK_WIRE_INPUT_ADAPTER.validate_python(payload) + + +_SPECIFIC_OUTPUTS = [ + { + "hookEventName": "SessionStart", + "additionalContext": "Use the project environment", + "watchPaths": ["/workspace/src"], + }, + { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": "Protected path", + }, + { + "hookEventName": "PermissionRequest", + "decision": { + "behavior": "allow", + "updatedPermissions": [ + { + "type": "addRules", + "rules": [{"toolName": "Bash", "ruleContent": "git status"}], + "behavior": "allow", + "destination": "session", + } + ], + }, + }, + { + "hookEventName": "PostToolUse", + "additionalContext": "Check the formatter output", + "updatedMCPToolOutput": {"content": "deferred"}, + }, + { + "hookEventName": "Stop", + "additionalContext": "Finish the remaining task", + }, + { + "hookEventName": "SubagentStart", + "additionalContext": "Focus on tests", + }, + { + "hookEventName": "SubagentStop", + "additionalContext": "Verify the subagent result", + }, +] + + +@pytest.mark.parametrize("specific_output", _SPECIFIC_OUTPUTS) +def test_wire_outputs_round_trip_with_aliases( + specific_output: dict[str, object], +) -> None: + payload = { + "continue": False, + "stopReason": "Stopped by hook", + "hookSpecificOutput": specific_output, + } + + parsed = HOOK_WIRE_OUTPUT_ADAPTER.validate_python(payload) + + assert ( + HOOK_WIRE_OUTPUT_ADAPTER.dump_python( + parsed, + mode="json", + by_alias=True, + exclude_none=True, + exclude_defaults=True, + ) + == payload + ) + + +def test_wire_output_retains_unknown_fields() -> None: + payload = {"continue": True, "futureField": {"enabled": True}} + + parsed = HOOK_WIRE_OUTPUT_ADAPTER.validate_python(payload) + + assert parsed.model_extra == {"futureField": {"enabled": True}} + assert HOOK_WIRE_OUTPUT_ADAPTER.dump_python( + parsed, + mode="json", + by_alias=True, + exclude_defaults=True, + ) == {"futureField": {"enabled": True}} + + +def test_wire_output_does_not_apply_internal_field_names() -> None: + parsed = HOOK_WIRE_OUTPUT_ADAPTER.validate_python({"continue_": False}) + + assert parsed.continue_ is True + assert parsed.model_extra == {"continue_": False} + + +def test_wire_output_rejects_mismatched_specific_discriminator() -> None: + with pytest.raises(ValidationError): + HOOK_WIRE_OUTPUT_ADAPTER.validate_python( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "decision": {"behavior": "deny"}, + } + } + ) + + +def test_domain_event_union_selects_event_model() -> None: + event = HOOK_DOMAIN_EVENT_ADAPTER.validate_python( + { + "event": "Notification", + "notification": { + "type": "approval_required", + "message": "Approval required", + }, + } + ) + + assert event.event is HookEvent.NOTIFICATION + + +def test_post_tool_use_accepts_native_tool_message() -> None: + result = ToolMessage(content="done", tool_call_id="call-1") + + event = PostToolUseEvent( + event=HookEvent.POST_TOOL_USE, + call=ToolCallData(id="call-1", name="write_file", args={}), + result=result, + ) + + assert event.result is result + + +def test_domain_models_reject_unknown_fields() -> None: + with pytest.raises(ValidationError): + HookContext.model_validate( + { + "thread_id": "thread-1", + "cwd": Path("/workspace"), + "approval_mode": ApprovalMode.MANUAL, + "unsupported": True, + } + ) + + +def test_decision_union_selects_event_model() -> None: + decision = HOOK_DECISION_ADAPTER.validate_python( + { + "event": "PreToolUse", + "permission": {"behavior": "ask"}, + "context": ["Explain the operation"], + } + ) + + assert decision.event is HookEvent.PRE_TOOL_USE + assert decision.permission == PermissionEffect(behavior="ask") + + +def test_hooks_config_validates_event_keys_and_aliases() -> None: + payload = { + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "./check.sh", + "timeout": 30, + "statusMessage": "Checking command", + } + ], + } + ] + } + } + + config = HOOKS_CONFIG_ADAPTER.validate_python(payload) + + assert config.hooks[HookEvent.PRE_TOOL_USE][0].hooks[0].status_message == ( + "Checking command" + ) + assert ( + HOOKS_CONFIG_ADAPTER.dump_python( + config, + mode="json", + by_alias=True, + exclude_none=True, + ) + == payload + ) + + +def test_hooks_config_rejects_unsupported_handler_type() -> None: + with pytest.raises(ValidationError): + HOOKS_CONFIG_ADAPTER.validate_python( + { + "hooks": { + "Stop": [ + { + "hooks": [ + { + "type": "http", + "command": "https://example.com", + } + ] + } + ] + } + } + ) + + +def test_transport_models_round_trip_typed_domain_payloads() -> None: + invocation_id = uuid4() + invocation = HookInvocation( + context=HookContext( + thread_id="thread-1", + cwd=Path("/workspace"), + approval_mode=ApprovalMode.MANUAL, + ), + event=SessionStartEvent( + event=HookEvent.SESSION_START, + cause=SessionStartCause.STARTUP, + ), + ) + request = HookInvocationRequest( + protocol_version=1, + invocation_id=invocation_id, + snapshot_id="snapshot-1", + run_id="run-1", + invocation=invocation, + deadline=datetime(2026, 7, 20, tzinfo=UTC), + ) + response = HookInvocationResponse( + protocol_version=1, + invocation_id=invocation_id, + snapshot_id="snapshot-1", + decision=SessionStartDecision( + event=HookEvent.SESSION_START, + context=["Loaded project context"], + ), + ) + + request_json = HOOK_INVOCATION_REQUEST_ADAPTER.dump_json(request) + response_json = HOOK_INVOCATION_RESPONSE_ADAPTER.dump_json(response) + + assert HOOK_INVOCATION_REQUEST_ADAPTER.validate_json(request_json) == request + assert HOOK_INVOCATION_RESPONSE_ADAPTER.validate_json(response_json) == response + assert UUID(str(response.invocation_id)) == invocation_id diff --git a/libs/code/tests/unit_tests/test_hooks.py b/libs/code/tests/unit_tests/test_hooks.py index e62ec903233..8a16708c259 100644 --- a/libs/code/tests/unit_tests/test_hooks.py +++ b/libs/code/tests/unit_tests/test_hooks.py @@ -14,7 +14,7 @@ if TYPE_CHECKING: from collections.abc import Generator -import deepagents_code.hooks as hooks_mod +import deepagents_code.hooks.legacy as hooks_mod @pytest.fixture(autouse=True) diff --git a/libs/code/tests/unit_tests/test_json_types.py b/libs/code/tests/unit_tests/test_json_types.py index 8600b44876d..c6fba5f3eb4 100644 --- a/libs/code/tests/unit_tests/test_json_types.py +++ b/libs/code/tests/unit_tests/test_json_types.py @@ -1,6 +1,14 @@ -"""Tests for shared JSON type aliases.""" +"""Tests for shared JSON type aliases and validators.""" -from deepagents_code.json_types import JsonObject, JsonValue +import pytest +from pydantic import ValidationError + +from deepagents_code.json_types import ( + JSON_OBJECT_ADAPTER, + JSON_VALUE_ADAPTER, + JsonObject, + JsonValue, +) from deepagents_code.plugins.models import ( JsonObject as PluginJsonObject, JsonValue as PluginJsonValue, @@ -11,3 +19,17 @@ def test_plugin_json_types_are_compatibility_reexports() -> None: """Plugin imports resolve to the canonical shared aliases.""" assert PluginJsonValue is JsonValue assert PluginJsonObject is JsonObject + + +def test_json_adapters_validate_recursive_values() -> None: + """Cached adapters validate recursive JSON values and objects.""" + value = {"nested": [1, True, None, {"name": "dcode"}]} + + assert JSON_VALUE_ADAPTER.validate_python(value) == value + assert JSON_OBJECT_ADAPTER.validate_python(value) == value + + +def test_json_object_adapter_rejects_non_object_root() -> None: + """Object validation rejects a JSON array at the root.""" + with pytest.raises(ValidationError): + JSON_OBJECT_ADAPTER.validate_python(["not", "an", "object"]) From 8400dd24cc63ec9aae048d53423d03d8d47dc612 Mon Sep 17 00:00:00 2001 From: Johannes du Plessis <51395795+johannes117@users.noreply.github.com> Date: Tue, 21 Jul 2026 00:44:57 +0000 Subject: [PATCH 2/6] feat(code): add Hooks v2 execution engine Implement immutable matching, compatible wire projection, bounded command execution, and event-aware decision reduction behind the typed hook contracts. Co-authored-by: open-swe[bot] --- libs/code/deepagents_code/hooks/__init__.py | 4 +- libs/code/deepagents_code/hooks/engine.py | 71 ++ libs/code/deepagents_code/hooks/projection.py | 225 ++++++ libs/code/deepagents_code/hooks/reducer.py | 276 +++++++ libs/code/deepagents_code/hooks/runner.py | 239 ++++++ libs/code/deepagents_code/hooks/snapshot.py | 147 ++++ .../tests/unit_tests/hooks/test_engine.py | 763 ++++++++++++++++++ 7 files changed, 1724 insertions(+), 1 deletion(-) create mode 100644 libs/code/deepagents_code/hooks/engine.py create mode 100644 libs/code/deepagents_code/hooks/projection.py create mode 100644 libs/code/deepagents_code/hooks/reducer.py create mode 100644 libs/code/deepagents_code/hooks/runner.py create mode 100644 libs/code/deepagents_code/hooks/snapshot.py create mode 100644 libs/code/tests/unit_tests/hooks/test_engine.py diff --git a/libs/code/deepagents_code/hooks/__init__.py b/libs/code/deepagents_code/hooks/__init__.py index 502ea93819e..70d34bc0a45 100644 --- a/libs/code/deepagents_code/hooks/__init__.py +++ b/libs/code/deepagents_code/hooks/__init__.py @@ -1,5 +1,6 @@ -"""Hook contracts and compatibility dispatch.""" +"""Hook contracts, execution engine, and compatibility dispatch.""" +from deepagents_code.hooks.engine import HookEngine from deepagents_code.hooks.legacy import ( HOOK_SUBPROCESS_TIMEOUT, HOOK_TOOL_OUTPUT_LIMIT, @@ -16,6 +17,7 @@ __all__ = [ "HOOK_SUBPROCESS_TIMEOUT", "HOOK_TOOL_OUTPUT_LIMIT", + "HookEngine", "_background_tasks", "dispatch_hook", "dispatch_hook_fire_and_forget", diff --git a/libs/code/deepagents_code/hooks/engine.py b/libs/code/deepagents_code/hooks/engine.py new file mode 100644 index 00000000000..53f383d564d --- /dev/null +++ b/libs/code/deepagents_code/hooks/engine.py @@ -0,0 +1,71 @@ +"""Standalone orchestration for the Hooks v2 execution engine.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from deepagents_code.hooks.models.domain import HookDiagnostic +from deepagents_code.hooks.projection import serialize_hook_input +from deepagents_code.hooks.reducer import reduce_hook_results +from deepagents_code.hooks.runner import ( + DEFAULT_HOOK_TIMEOUT, + MAX_HOOK_OUTPUT_BYTES, + HandlerResult, + run_command_handler, +) + +if TYPE_CHECKING: + from deepagents_code.hooks.models.domain import HookDecision, HookInvocation + from deepagents_code.hooks.snapshot import HooksSnapshot + + +@dataclass(frozen=True, slots=True) +class HookEngine: + """Execute Hooks v2 invocations against one immutable snapshot.""" + + snapshot: HooksSnapshot + default_timeout: float = DEFAULT_HOOK_TIMEOUT + max_output_bytes: int = MAX_HOOK_OUTPUT_BYTES + + async def run(self, invocation: HookInvocation) -> HookDecision: + """Execute matching handlers and return a normalized decision. + + Args: + invocation: Native lifecycle invocation. + + Returns: + The event-specific decision produced by ordered hook reduction. + """ + match = self.snapshot.match(invocation) + try: + payload = serialize_hook_input(invocation) + except (TypeError, ValueError) as exc: + diagnostic = HookDiagnostic( + code="projection_failed", + severity="warning", + message=f"Could not project hook invocation: {exc}", + ) + return reduce_hook_results( + invocation, + (), + diagnostics=(*match.diagnostics, diagnostic), + ) + + results: list[HandlerResult] = [] + for handler in match.handlers: + result = await run_command_handler( + handler, + payload, + cwd=invocation.context.cwd, + default_timeout=self.default_timeout, + max_output_bytes=self.max_output_bytes, + ) + results.append(result) + if result.output is not None and not result.output.continue_: + break + return reduce_hook_results( + invocation, + results, + diagnostics=match.diagnostics, + ) diff --git a/libs/code/deepagents_code/hooks/projection.py b/libs/code/deepagents_code/hooks/projection.py new file mode 100644 index 00000000000..c7ad64ee7e0 --- /dev/null +++ b/libs/code/deepagents_code/hooks/projection.py @@ -0,0 +1,225 @@ +"""Projection from Hooks v2 domain invocations to compatible wire input.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, NotRequired, TypedDict + +from langchain_core.messages import ToolMessage + +from deepagents_code.approval_mode import ApprovalMode +from deepagents_code.hooks.models.adapters import HOOK_WIRE_INPUT_ADAPTER +from deepagents_code.hooks.models.domain import ( + HookEvent, + NotificationEvent, + PermissionRequestEvent, + PostToolUseEvent, + PreToolUseEvent, + SessionEndEvent, + SessionStartEvent, + StopEvent, + SubagentStartEvent, + SubagentStopEvent, +) +from deepagents_code.hooks.models.wire import ( + BackgroundTaskWire, + Effort, + NotificationWireInput, + PermissionRequestWireInput, + PostToolUseWireInput, + PreToolUseWireInput, + SessionCronWire, + SessionEndWireInput, + SessionStartWireInput, + StopWireInput, + SubagentStartWireInput, + SubagentStopWireInput, + WireNotificationType, + WirePermissionMode, +) +from deepagents_code.json_types import JSON_VALUE_ADAPTER, JsonValue + +if TYPE_CHECKING: + from pathlib import Path + from uuid import UUID + + from langgraph.types import Command + + from deepagents_code.hooks.models.domain import HookInvocation + from deepagents_code.hooks.models.wire import HookWireInput + + +class _CommonWireFields(TypedDict): + session_id: str + transcript_path: str + cwd: str + prompt_id: NotRequired[UUID | None] + permission_mode: WirePermissionMode + effort: NotRequired[Effort | None] + + +def project_hook_input(invocation: HookInvocation) -> HookWireInput: + """Project a native hook invocation into the compatible wire contract. + + Args: + invocation: Native lifecycle invocation. + + Returns: + A validated event-specific wire input. + + Raises: + TypeError: If the invocation carries an unsupported event model. + """ + context = invocation.context + event = invocation.event + if isinstance(event, SessionStartEvent): + result = SessionStartWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.SESSION_START, + source=event.cause, + model=event.model, + ) + elif isinstance(event, SessionEndEvent): + result = SessionEndWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.SESSION_END, + reason=event.cause, + ) + elif isinstance(event, PermissionRequestEvent): + result = PermissionRequestWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.PERMISSION_REQUEST, + tool_name=event.call.name, + tool_input=event.call.args, + ) + elif isinstance(event, NotificationEvent): + result = NotificationWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.NOTIFICATION, + message=event.notification.message, + title=event.notification.title, + notification_type=_notification_type(event.notification.type), + ) + elif isinstance(event, PreToolUseEvent): + result = PreToolUseWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.PRE_TOOL_USE, + tool_name=event.call.name, + tool_input=event.call.args, + tool_use_id=event.call.id, + ) + elif isinstance(event, PostToolUseEvent): + result = PostToolUseWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.POST_TOOL_USE, + tool_name=event.call.name, + tool_input=event.call.args, + tool_response=_tool_result(event.result), + tool_use_id=event.call.id, + duration_ms=event.duration_ms, + ) + elif isinstance(event, StopEvent): + result = StopWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.STOP, + stop_hook_active=event.continuation_count > 0, + last_assistant_message=event.last_assistant_message, + background_tasks=[ + BackgroundTaskWire.model_validate(task.model_dump()) + for task in event.background_tasks + ], + session_crons=[ + SessionCronWire.model_validate(cron.model_dump()) + for cron in event.session_crons + ], + ) + elif isinstance(event, SubagentStartEvent): + result = SubagentStartWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.SUBAGENT_START, + agent_id=event.agent.id, + agent_type=event.agent.name, + ) + elif isinstance(event, SubagentStopEvent): + result = SubagentStopWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.SUBAGENT_STOP, + stop_hook_active=event.continuation_count > 0, + agent_id=event.agent.id, + agent_type=event.agent.name, + agent_transcript_path=str(_transcript_path(context.cwd, event.agent.id)), + last_assistant_message=event.last_assistant_message, + background_tasks=[ + BackgroundTaskWire.model_validate(task.model_dump()) + for task in event.background_tasks + ], + session_crons=[ + SessionCronWire.model_validate(cron.model_dump()) + for cron in event.session_crons + ], + ) + else: + msg = f"Unsupported hook event: {type(event).__name__}" + raise TypeError(msg) + + payload = HOOK_WIRE_INPUT_ADAPTER.dump_python( + result, + mode="json", + by_alias=True, + exclude_none=True, + ) + return HOOK_WIRE_INPUT_ADAPTER.validate_python(payload) + + +def _common_fields(invocation: HookInvocation) -> _CommonWireFields: + context = invocation.context + return { + "session_id": context.thread_id, + "transcript_path": str(_transcript_path(context.cwd, context.thread_id)), + "cwd": str(context.cwd), + "prompt_id": context.prompt_id, + "permission_mode": _permission_mode(context.approval_mode), + "effort": Effort(level=context.effort) if context.effort is not None else None, + } + + +def serialize_hook_input(invocation: HookInvocation) -> bytes: + """Serialize a hook invocation as validated compatible JSON. + + Args: + invocation: Native lifecycle invocation. + + Returns: + Compact JSON bytes suitable for command stdin. + """ + return HOOK_WIRE_INPUT_ADAPTER.dump_json( + project_hook_input(invocation), + by_alias=True, + exclude_none=True, + ) + + +def _permission_mode(mode: ApprovalMode) -> WirePermissionMode: + return { + ApprovalMode.MANUAL: WirePermissionMode.DEFAULT, + ApprovalMode.AUTO: WirePermissionMode.AUTO, + ApprovalMode.YOLO: WirePermissionMode.BYPASS_PERMISSIONS, + }[mode] + + +def _notification_type(value: str) -> WireNotificationType: + try: + return WireNotificationType(value) + except ValueError: + return WireNotificationType.AGENT_NEEDS_INPUT + + +def _transcript_path(cwd: Path, identifier: str) -> Path: + return cwd / ".deepagents" / "transcripts" / f"{identifier}.jsonl" + + +def _tool_result(result: ToolMessage | Command[str]) -> JsonValue: + if isinstance(result, ToolMessage): + value: object = result.model_dump(mode="json") + else: + value = JSON_VALUE_ADAPTER.dump_python(result, mode="json", warnings=False) + return JSON_VALUE_ADAPTER.validate_python(value) diff --git a/libs/code/deepagents_code/hooks/reducer.py b/libs/code/deepagents_code/hooks/reducer.py new file mode 100644 index 00000000000..4219dcfb10c --- /dev/null +++ b/libs/code/deepagents_code/hooks/reducer.py @@ -0,0 +1,276 @@ +"""Event-aware reduction for Hooks v2 command output.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +from deepagents_code.hooks.models.domain import ( + HookDecision, + HookDiagnostic, + HookEvent, + NotificationDecision, + PermissionEffect, + PermissionRequestDecision, + PostToolUseDecision, + PreToolUseDecision, + SessionEndDecision, + SessionStartDecision, + StopDecision, + StopEvent, + SubagentStartDecision, + SubagentStopDecision, + SubagentStopEvent, +) +from deepagents_code.hooks.models.wire import ( + PermissionRequestSpecificOutput, + PostToolUseSpecificOutput, + PreToolUseSpecificOutput, + SessionStartSpecificOutput, + StopSpecificOutput, + SubagentStartSpecificOutput, + SubagentStopSpecificOutput, +) + +if TYPE_CHECKING: + from collections.abc import Iterable + + from deepagents_code.hooks.models.domain import HookInvocation + from deepagents_code.hooks.models.wire import HookWireOutput + from deepagents_code.hooks.runner import HandlerResult + +_PERMISSION_RANK = {"none": 0, "allow": 1, "ask": 2, "deny": 3} + + +@dataclass(slots=True) +class _Reduction: + continue_processing: bool = True + stop_reason: str | None = None + user_notices: list[str] = field(default_factory=list) + terminal_sequences: list[str] = field(default_factory=list) + diagnostics: list[HookDiagnostic] = field(default_factory=list) + context: list[str] = field(default_factory=list) + feedback: list[str] = field(default_factory=list) + permission: PermissionEffect = field( + default_factory=lambda: PermissionEffect(behavior="none") + ) + continue_loop: bool = False + + +def reduce_hook_results( + invocation: HookInvocation, + results: Iterable[HandlerResult], + *, + diagnostics: Iterable[HookDiagnostic] = (), +) -> HookDecision: + """Reduce ordered handler results into an event-specific decision. + + Args: + invocation: Native event being processed. + results: Handler results in configuration order. + diagnostics: Snapshot or orchestration diagnostics to retain. + + Returns: + The normalized decision for the invocation event. + """ + state = _Reduction(diagnostics=list(diagnostics)) + for result in results: + state.diagnostics.extend(result.diagnostics) + if result.output is not None: + _merge_output(invocation, state, result.handler_id, result.output) + if not state.continue_processing: + break + return _decision(invocation, state) + + +def _merge_output( + invocation: HookInvocation, + state: _Reduction, + handler_id: str, + output: HookWireOutput, +) -> None: + state.continue_processing = output.continue_ + if output.stop_reason is not None: + state.stop_reason = output.stop_reason + if output.system_message is not None and not output.suppress_output: + state.user_notices.append(output.system_message) + if output.terminal_sequence is not None: + state.terminal_sequences.append(output.terminal_sequence) + if output.decision == "block": + _merge_block(invocation, state, output.reason) + + specific = output.hook_specific_output + if specific is None: + return + if specific.hook_event_name != invocation.event.event.value: + state.diagnostics.append( + HookDiagnostic( + code="mismatched_output", + severity="warning", + message="Hook-specific output does not match the invoked event", + handler_id=handler_id, + field="hookSpecificOutput.hookEventName", + ) + ) + return + _merge_specific(invocation, state, specific) + + +def _merge_block( + invocation: HookInvocation, + state: _Reduction, + reason: str | None, +) -> None: + message = reason or "Blocked by hook" + event = invocation.event.event + if event in {HookEvent.PERMISSION_REQUEST, HookEvent.PRE_TOOL_USE}: + _merge_permission(state, PermissionEffect(behavior="deny", reason=message)) + elif event is HookEvent.STOP: + if ( + isinstance(invocation.event, StopEvent) + and invocation.event.continuation_count + ): + state.diagnostics.append(_loop_guard_diagnostic()) + else: + state.continue_loop = True + state.feedback.append(message) + elif event is HookEvent.POST_TOOL_USE: + state.feedback.append(message) + elif event is HookEvent.SUBAGENT_STOP: + if ( + isinstance(invocation.event, SubagentStopEvent) + and invocation.event.continuation_count + ): + state.diagnostics.append(_loop_guard_diagnostic()) + else: + state.context.append(message) + else: + state.stop_reason = message + state.continue_processing = False + + +def _merge_specific( + invocation: HookInvocation, + state: _Reduction, + specific: object, +) -> None: + if isinstance(specific, SessionStartSpecificOutput): + _append(state.context, specific.additional_context) + elif isinstance(specific, PreToolUseSpecificOutput): + _append(state.context, specific.additional_context) + behavior = specific.permission_decision + if behavior is not None: + normalized = "none" if behavior == "defer" else behavior + _merge_permission( + state, + PermissionEffect( + behavior=normalized, + reason=specific.permission_decision_reason, + ), + ) + elif isinstance(specific, PermissionRequestSpecificOutput): + decision = specific.decision + if decision.behavior == "allow": + _merge_permission(state, PermissionEffect(behavior="allow")) + else: + _merge_permission( + state, + PermissionEffect( + behavior="deny", + reason=decision.message, + interrupt=decision.interrupt, + ), + ) + elif isinstance(specific, PostToolUseSpecificOutput): + _append(state.context, specific.additional_context) + elif isinstance(specific, StopSpecificOutput): + if specific.additional_context is not None: + if ( + isinstance(invocation.event, StopEvent) + and invocation.event.continuation_count + ): + state.diagnostics.append(_loop_guard_diagnostic()) + else: + state.continue_loop = True + state.feedback.append(specific.additional_context) + elif isinstance(specific, SubagentStartSpecificOutput): + _append(state.context, specific.additional_context) + elif ( + isinstance(specific, SubagentStopSpecificOutput) + and specific.additional_context is not None + ): + if ( + isinstance(invocation.event, SubagentStopEvent) + and invocation.event.continuation_count + ): + state.diagnostics.append(_loop_guard_diagnostic()) + else: + state.context.append(specific.additional_context) + + +def _merge_permission(state: _Reduction, effect: PermissionEffect) -> None: + if _PERMISSION_RANK[effect.behavior] >= _PERMISSION_RANK[state.permission.behavior]: + state.permission = effect + + +def _decision(invocation: HookInvocation, state: _Reduction) -> HookDecision: + common = { + "continue_processing": state.continue_processing, + "stop_reason": state.stop_reason, + "user_notices": state.user_notices, + "terminal_sequences": state.terminal_sequences, + "diagnostics": state.diagnostics, + } + event = invocation.event.event + if event is HookEvent.SESSION_START: + return SessionStartDecision(event=event, context=state.context, **common) + if event is HookEvent.SESSION_END: + return SessionEndDecision(event=event, **common) + if event is HookEvent.PERMISSION_REQUEST: + return PermissionRequestDecision( + event=event, + permission=state.permission, + **common, + ) + if event is HookEvent.NOTIFICATION: + return NotificationDecision(event=event, **common) + if event is HookEvent.PRE_TOOL_USE: + return PreToolUseDecision( + event=event, + permission=state.permission, + context=state.context, + **common, + ) + if event is HookEvent.POST_TOOL_USE: + return PostToolUseDecision( + event=event, + feedback=state.feedback, + context=state.context, + **common, + ) + if event is HookEvent.STOP: + return StopDecision( + event=event, + continue_loop=state.continue_loop, + feedback=state.feedback, + **common, + ) + if event is HookEvent.SUBAGENT_START: + return SubagentStartDecision(event=event, context=state.context, **common) + if event is HookEvent.SUBAGENT_STOP: + return SubagentStopDecision(event=event, context=state.context, **common) + msg = f"Unsupported hook event: {event}" + raise ValueError(msg) + + +def _append(values: list[str], value: str | None) -> None: + if value is not None: + values.append(value) + + +def _loop_guard_diagnostic() -> HookDiagnostic: + return HookDiagnostic( + code="continuation_guard", + severity="warning", + message="Ignored recursive stop-hook continuation", + ) diff --git a/libs/code/deepagents_code/hooks/runner.py b/libs/code/deepagents_code/hooks/runner.py new file mode 100644 index 00000000000..e8d379196f8 --- /dev/null +++ b/libs/code/deepagents_code/hooks/runner.py @@ -0,0 +1,239 @@ +"""Bounded asynchronous command execution for Hooks v2.""" + +from __future__ import annotations + +import asyncio +import json +import os +import shlex +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pydantic import ValidationError + +from deepagents_code.hooks.models.adapters import HOOK_WIRE_OUTPUT_ADAPTER +from deepagents_code.hooks.models.domain import HookDiagnostic +from deepagents_code.hooks.models.wire import HookWireOutput + +if TYPE_CHECKING: + from asyncio.subprocess import Process + from pathlib import Path + + from deepagents_code.hooks.snapshot import HookHandler + +DEFAULT_HOOK_TIMEOUT = 10.0 +MAX_HOOK_OUTPUT_BYTES = 100_000 +_READ_CHUNK_BYTES = 8192 +_BLOCKING_EXIT_CODE = 2 + + +@dataclass(frozen=True, slots=True) +class HandlerResult: + """Validated output and diagnostics from one command handler.""" + + handler_id: str + output: HookWireOutput | None = None + diagnostics: tuple[HookDiagnostic, ...] = () + + +async def run_command_handler( + handler: HookHandler, + payload: bytes, + *, + cwd: Path, + default_timeout: float = DEFAULT_HOOK_TIMEOUT, + max_output_bytes: int = MAX_HOOK_OUTPUT_BYTES, +) -> HandlerResult: + """Run one hook command with bounded time and captured output. + + Args: + handler: Snapshotted command handler. + payload: Validated JSON sent to stdin. + cwd: Working directory inherited from the invocation. + default_timeout: Timeout used when the handler has no override. + max_output_bytes: Maximum retained bytes for each output stream. + + Returns: + Validated protocol output and structured diagnostics. + + Raises: + asyncio.CancelledError: If the caller cancels command execution. + """ + try: + argv = shlex.split(handler.command) + except ValueError as exc: + return _failure(handler.id, "invalid_command", f"Invalid hook command: {exc}") + if not argv: + return _failure(handler.id, "invalid_command", "Hook command is empty") + + try: + process = await asyncio.create_subprocess_exec( + *argv, + cwd=cwd, + env=os.environ.copy(), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + except (OSError, ValueError) as exc: + return _failure(handler.id, "launch_failed", f"Could not launch hook: {exc}") + + timeout = handler.timeout if handler.timeout is not None else default_timeout + try: + stdout, stderr, stdout_truncated, stderr_truncated = await asyncio.wait_for( + _communicate_bounded(process, payload, max_output_bytes), + timeout=timeout, + ) + except TimeoutError: + await _terminate(process) + return _failure( + handler.id, + "timeout", + f"Hook exceeded its {timeout:g} second timeout", + ) + except asyncio.CancelledError: + await _terminate(process) + raise + except (BrokenPipeError, ConnectionResetError) as exc: + await _terminate(process) + return _failure(handler.id, "io_failed", f"Hook communication failed: {exc}") + + diagnostics: list[HookDiagnostic] = [] + if stdout_truncated: + diagnostics.append( + _diagnostic( + handler.id, + "stdout_truncated", + f"Hook stdout exceeded {max_output_bytes} bytes", + ) + ) + if stderr_truncated: + diagnostics.append( + _diagnostic( + handler.id, + "stderr_truncated", + f"Hook stderr exceeded {max_output_bytes} bytes", + ) + ) + + if process.returncode == _BLOCKING_EXIT_CODE: + reason = _decode(stderr).strip() or "Hook blocked the operation" + return HandlerResult( + handler_id=handler.id, + output=HookWireOutput(decision="block", reason=reason), + diagnostics=tuple(diagnostics), + ) + if process.returncode != 0: + diagnostics.append( + _diagnostic( + handler.id, + "nonzero_exit", + f"Hook exited with status {process.returncode}", + ) + ) + return HandlerResult(handler_id=handler.id, diagnostics=tuple(diagnostics)) + if not stdout.strip(): + return HandlerResult(handler_id=handler.id, diagnostics=tuple(diagnostics)) + + try: + decoded = json.loads(stdout) + except (json.JSONDecodeError, UnicodeDecodeError): + diagnostics.append( + _diagnostic(handler.id, "malformed_json", "Hook output is not valid JSON") + ) + return HandlerResult(handler_id=handler.id, diagnostics=tuple(diagnostics)) + try: + output = HOOK_WIRE_OUTPUT_ADAPTER.validate_python(decoded) + except ValidationError as exc: + diagnostics.append( + _diagnostic( + handler.id, + "invalid_output", + f"Hook output failed protocol validation: {exc.title}", + ) + ) + return HandlerResult(handler_id=handler.id, diagnostics=tuple(diagnostics)) + return HandlerResult( + handler_id=handler.id, + output=output, + diagnostics=tuple(diagnostics), + ) + + +async def _communicate_bounded( + process: Process, + payload: bytes, + limit: int, +) -> tuple[bytes, bytes, bool, bool]: + if process.stdin is None or process.stdout is None or process.stderr is None: + msg = "Hook process pipes are unavailable" + raise BrokenPipeError(msg) + stdout_task = asyncio.create_task(_read_bounded(process.stdout, limit)) + stderr_task = asyncio.create_task(_read_bounded(process.stderr, limit)) + stdin_task = asyncio.create_task(_write_input(process, payload)) + try: + await process.wait() + stdout, stderr = await asyncio.gather(stdout_task, stderr_task) + await stdin_task + except BaseException: + stdin_task.cancel() + stdout_task.cancel() + stderr_task.cancel() + await asyncio.gather( + stdin_task, + stdout_task, + stderr_task, + return_exceptions=True, + ) + raise + return stdout[0], stderr[0], stdout[1], stderr[1] + + +async def _write_input(process: Process, payload: bytes) -> None: + if process.stdin is None: + msg = "Hook process stdin is unavailable" + raise BrokenPipeError(msg) + process.stdin.write(payload) + await process.stdin.drain() + process.stdin.close() + + +async def _read_bounded( + stream: asyncio.StreamReader, + limit: int, +) -> tuple[bytes, bool]: + retained = bytearray() + truncated = False + while chunk := await stream.read(_READ_CHUNK_BYTES): + remaining = limit - len(retained) + if remaining > 0: + retained.extend(chunk[:remaining]) + if len(chunk) > remaining: + truncated = True + return bytes(retained), truncated + + +async def _terminate(process: Process) -> None: + if process.returncode is None: + process.kill() + await process.wait() + + +def _decode(value: bytes) -> str: + return value.decode("utf-8", errors="replace") + + +def _failure(handler_id: str, code: str, message: str) -> HandlerResult: + return HandlerResult( + handler_id=handler_id, + diagnostics=(_diagnostic(handler_id, code, message),), + ) + + +def _diagnostic(handler_id: str, code: str, message: str) -> HookDiagnostic: + return HookDiagnostic( + code=code, + severity="warning", + message=message, + handler_id=handler_id, + ) diff --git a/libs/code/deepagents_code/hooks/snapshot.py b/libs/code/deepagents_code/hooks/snapshot.py new file mode 100644 index 00000000000..61b68fff580 --- /dev/null +++ b/libs/code/deepagents_code/hooks/snapshot.py @@ -0,0 +1,147 @@ +"""Immutable runtime snapshots for Hooks v2 configuration.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from types import MappingProxyType +from typing import TYPE_CHECKING + +from deepagents_code.hooks.models.domain import ( + HookDiagnostic, + HookEvent, + NotificationEvent, + PermissionRequestEvent, + PostToolUseEvent, + PreToolUseEvent, +) + +if TYPE_CHECKING: + from collections.abc import Mapping + from re import Pattern + + from deepagents_code.hooks.models.config import HooksConfig + from deepagents_code.hooks.models.domain import HookInvocation + +_MATCHABLE_EVENTS = frozenset( + { + HookEvent.PERMISSION_REQUEST, + HookEvent.NOTIFICATION, + HookEvent.PRE_TOOL_USE, + HookEvent.POST_TOOL_USE, + } +) + + +@dataclass(frozen=True, slots=True) +class HookHandler: + """One ordered command handler in a configuration snapshot.""" + + id: str + event: HookEvent + command: str + timeout: float | None + status_message: str | None + matcher: Pattern[str] | None + matcher_text: str | None + matcher_error: str | None = None + + +@dataclass(frozen=True, slots=True) +class HookMatch: + """Matched handlers and configuration diagnostics for one invocation.""" + + handlers: tuple[HookHandler, ...] + diagnostics: tuple[HookDiagnostic, ...] + + +@dataclass(frozen=True, slots=True) +class HooksSnapshot: + """Immutable, declaration-ordered Hooks v2 runtime configuration.""" + + handlers: Mapping[HookEvent, tuple[HookHandler, ...]] + + @classmethod + def from_config(cls, config: HooksConfig) -> HooksSnapshot: + """Build an immutable runtime snapshot from validated configuration. + + Args: + config: Validated Hooks v2 configuration. + + Returns: + A snapshot whose handler order and matchers cannot change in flight. + """ + expanded: dict[HookEvent, tuple[HookHandler, ...]] = {} + for event, groups in config.hooks.items(): + handlers: list[HookHandler] = [] + for group_index, group in enumerate(groups): + matcher, error = _compile_matcher(group.matcher) + for handler_index, spec in enumerate(group.hooks): + handlers.append( + HookHandler( + id=f"{event.value}:{group_index}:{handler_index}", + event=event, + command=spec.command, + timeout=spec.timeout, + status_message=spec.status_message, + matcher=matcher, + matcher_text=group.matcher, + matcher_error=error, + ) + ) + expanded[event] = tuple(handlers) + return cls(handlers=MappingProxyType(expanded)) + + def match(self, invocation: HookInvocation) -> HookMatch: + """Return handlers matching an invocation in declaration order. + + Args: + invocation: Domain invocation to match. + + Returns: + Matching handlers and diagnostics for invalid configured matchers. + """ + event = invocation.event.event + target = _match_target(invocation) + matched: list[HookHandler] = [] + diagnostics: list[HookDiagnostic] = [] + for handler in self.handlers.get(event, ()): + if handler.matcher_error is not None: + diagnostics.append( + HookDiagnostic( + code="invalid_matcher", + severity="warning", + message=handler.matcher_error, + handler_id=handler.id, + field="matcher", + ) + ) + continue + if ( + event not in _MATCHABLE_EVENTS + or handler.matcher is None + or (target is not None and handler.matcher.search(target) is not None) + ): + matched.append(handler) + return HookMatch(handlers=tuple(matched), diagnostics=tuple(diagnostics)) + + +def _compile_matcher(value: str | None) -> tuple[Pattern[str] | None, str | None]: + if not value: + return None, None + try: + return re.compile(value), None + except re.error as exc: + return None, f"Invalid hook matcher {value!r}: {exc}" + + +def _match_target(invocation: HookInvocation) -> str | None: + event = invocation.event + if isinstance( + event, + PermissionRequestEvent | PreToolUseEvent | PostToolUseEvent, + ): + return event.call.name + if isinstance(event, NotificationEvent): + return event.notification.type + return None diff --git a/libs/code/tests/unit_tests/hooks/test_engine.py b/libs/code/tests/unit_tests/hooks/test_engine.py new file mode 100644 index 00000000000..a5b534819f2 --- /dev/null +++ b/libs/code/tests/unit_tests/hooks/test_engine.py @@ -0,0 +1,763 @@ +"""Unit tests for the Hooks v2 execution engine.""" + +from __future__ import annotations + +import json +import sys +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest +from langchain_core.messages import ToolMessage +from langgraph.types import Command + +from deepagents_code.approval_mode import ApprovalMode +from deepagents_code.hooks import HookEngine, dispatch_hook +from deepagents_code.hooks.models.adapters import HOOK_WIRE_INPUT_ADAPTER +from deepagents_code.hooks.models.config import HooksConfig +from deepagents_code.hooks.models.domain import ( + AgentIdentity, + DcodeNotification, + HookContext, + HookDiagnostic, + HookEvent, + HookInvocation, + NotificationEvent, + PermissionRequestDecision, + PermissionRequestEvent, + PostToolUseDecision, + PostToolUseEvent, + PreToolUseDecision, + PreToolUseEvent, + SessionEndCause, + SessionEndEvent, + SessionStartCause, + SessionStartDecision, + SessionStartEvent, + StopDecision, + StopEvent, + SubagentStartDecision, + SubagentStartEvent, + SubagentStopDecision, + SubagentStopEvent, + ToolCallData, +) +from deepagents_code.hooks.models.wire import HookWireOutput +from deepagents_code.hooks.projection import project_hook_input, serialize_hook_input +from deepagents_code.hooks.reducer import reduce_hook_results +from deepagents_code.hooks.runner import HandlerResult, run_command_handler +from deepagents_code.hooks.snapshot import HookHandler, HooksSnapshot + +if TYPE_CHECKING: + from pathlib import Path + + from deepagents_code.hooks.models.domain import HookDomainEvent + + +def _context(tmp_path: Path, *, agent: AgentIdentity | None = None) -> HookContext: + return HookContext( + thread_id="thread-1", + cwd=tmp_path, + prompt_id=uuid4(), + approval_mode=ApprovalMode.MANUAL, + effort="high", + agent=agent, + ) + + +def _invocation(tmp_path: Path, event: HookDomainEvent) -> HookInvocation: + return HookInvocation(context=_context(tmp_path), event=event) + + +def _config(hooks: dict[str, object]) -> HooksConfig: + return HooksConfig.model_validate({"hooks": hooks}) + + +def _handler( + tmp_path: Path, + command: str, + *, + timeout: float | None = None, +) -> HookHandler: + snapshot = HooksSnapshot.from_config( + _config( + { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": command, + "timeout": timeout, + } + ] + } + ] + } + ) + ) + invocation = _invocation( + tmp_path, + SessionStartEvent( + event=HookEvent.SESSION_START, cause=SessionStartCause.STARTUP + ), + ) + return snapshot.match(invocation).handlers[0] + + +def test_snapshot_preserves_order_and_stable_ids(tmp_path: Path) -> None: + snapshot = HooksSnapshot.from_config( + _config( + { + "PreToolUse": [ + { + "matcher": "^Bash$", + "hooks": [ + {"type": "command", "command": "first"}, + {"type": "command", "command": "second"}, + ], + }, + {"hooks": [{"type": "command", "command": "all"}]}, + ] + } + ) + ) + invocation = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call-1", name="Bash", args={}), + ), + ) + + match = snapshot.match(invocation) + + assert [handler.command for handler in match.handlers] == [ + "first", + "second", + "all", + ] + assert [handler.id for handler in match.handlers] == [ + "PreToolUse:0:0", + "PreToolUse:0:1", + "PreToolUse:1:0", + ] + + +def test_snapshot_matches_notification_and_skips_tool_mismatch(tmp_path: Path) -> None: + snapshot = HooksSnapshot.from_config( + _config( + { + "Notification": [ + { + "matcher": "permission_.*", + "hooks": [{"type": "command", "command": "notify"}], + } + ], + "PermissionRequest": [ + { + "matcher": "Write", + "hooks": [{"type": "command", "command": "write"}], + } + ], + } + ) + ) + notification = _invocation( + tmp_path, + NotificationEvent( + event=HookEvent.NOTIFICATION, + notification=DcodeNotification( + type="permission_prompt", + message="Approve", + ), + ), + ) + permission = _invocation( + tmp_path, + PermissionRequestEvent( + event=HookEvent.PERMISSION_REQUEST, + call=ToolCallData(id="call-1", name="Bash", args={}), + ), + ) + + assert [item.command for item in snapshot.match(notification).handlers] == [ + "notify" + ] + assert snapshot.match(permission).handlers == () + + +def test_snapshot_reports_invalid_regex_and_runs_non_matchable_groups( + tmp_path: Path, +) -> None: + snapshot = HooksSnapshot.from_config( + _config( + { + "SessionEnd": [ + { + "matcher": "[", + "hooks": [{"type": "command", "command": "bad"}], + }, + { + "matcher": "ignored", + "hooks": [{"type": "command", "command": "good"}], + }, + ] + } + ) + ) + invocation = _invocation( + tmp_path, + SessionEndEvent(event=HookEvent.SESSION_END, cause=SessionEndCause.OTHER), + ) + + match = snapshot.match(invocation) + + assert [handler.command for handler in match.handlers] == ["good"] + assert [diagnostic.code for diagnostic in match.diagnostics] == ["invalid_matcher"] + + +@pytest.mark.parametrize( + ("event", "expected"), + [ + ( + SessionStartEvent( + event=HookEvent.SESSION_START, + cause=SessionStartCause.RESUME, + model="provider:model", + ), + {"hook_event_name": "SessionStart", "source": "resume"}, + ), + ( + SessionEndEvent(event=HookEvent.SESSION_END, cause=SessionEndCause.LOGOUT), + {"hook_event_name": "SessionEnd", "reason": "logout"}, + ), + ( + PermissionRequestEvent( + event=HookEvent.PERMISSION_REQUEST, + call=ToolCallData(id="call-1", name="Bash", args={"command": "pwd"}), + ), + {"hook_event_name": "PermissionRequest", "tool_name": "Bash"}, + ), + ( + NotificationEvent( + event=HookEvent.NOTIFICATION, + notification=DcodeNotification( + type="permission_prompt", + message="Approve", + ), + ), + { + "hook_event_name": "Notification", + "notification_type": "permission_prompt", + }, + ), + ( + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call-1", name="Write", args={}), + ), + {"hook_event_name": "PreToolUse", "tool_use_id": "call-1"}, + ), + ( + PostToolUseEvent( + event=HookEvent.POST_TOOL_USE, + call=ToolCallData(id="call-2", name="Bash", args={}), + result=ToolMessage(content="done", tool_call_id="call-2"), + ), + {"hook_event_name": "PostToolUse", "tool_use_id": "call-2"}, + ), + ( + StopEvent( + event=HookEvent.STOP, + continuation_count=1, + last_assistant_message="Done", + ), + {"hook_event_name": "Stop", "stop_hook_active": True}, + ), + ( + SubagentStartEvent( + event=HookEvent.SUBAGENT_START, + agent=AgentIdentity(id="agent-1", name="researcher"), + ), + {"hook_event_name": "SubagentStart", "agent_id": "agent-1"}, + ), + ( + SubagentStopEvent( + event=HookEvent.SUBAGENT_STOP, + agent=AgentIdentity(id="agent-1", name="researcher"), + continuation_count=0, + last_assistant_message="Done", + ), + {"hook_event_name": "SubagentStop", "agent_id": "agent-1"}, + ), + ], +) +def test_projects_all_wire_events( + tmp_path: Path, + event: HookDomainEvent, + expected: dict[str, object], +) -> None: + invocation = _invocation(tmp_path, event) + + payload = HOOK_WIRE_INPUT_ADAPTER.dump_python( + project_hook_input(invocation), + mode="json", + by_alias=True, + exclude_none=True, + ) + + assert payload.items() >= expected.items() + assert payload["session_id"] == "thread-1" + assert payload["permission_mode"] == "default" + assert payload["effort"] == {"level": "high"} + assert payload["transcript_path"].endswith("thread-1.jsonl") + + +def test_serializes_native_command_as_json(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + PostToolUseEvent.model_construct( + event=HookEvent.POST_TOOL_USE, + call=ToolCallData(id="call-1", name="Bash", args={}), + result=Command(update={"result": "done"}), + ), + ) + + payload = json.loads(serialize_hook_input(invocation)) + + assert payload["tool_response"]["update"] == {"result": "done"} + assert payload["tool_response"]["goto"] == [] + + +def test_serializes_native_tool_message_as_json(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + PostToolUseEvent( + event=HookEvent.POST_TOOL_USE, + call=ToolCallData(id="call-1", name="Bash", args={}), + result=ToolMessage( + content=[{"type": "text", "text": "done"}], + tool_call_id="call-1", + ), + ), + ) + + payload = json.loads(serialize_hook_input(invocation)) + + assert payload["tool_response"]["content"] == [{"type": "text", "text": "done"}] + + +async def test_runner_accepts_json_and_uses_invocation_cwd(tmp_path: Path) -> None: + code = "import json,os; print(json.dumps({'systemMessage': os.getcwd()}))" + handler = _handler(tmp_path, f"{sys.executable} -c {json.dumps(code)}") + + result = await run_command_handler(handler, b"{}", cwd=tmp_path) + + assert result.output is not None + assert result.output.system_message == str(tmp_path) + assert result.diagnostics == () + + +@pytest.mark.parametrize( + ("code", "expected_code"), + [ + ("pass", None), + ("print('not json')", "malformed_json"), + ("print('[]')", "invalid_output"), + ("raise SystemExit(3)", "nonzero_exit"), + ], +) +async def test_runner_protocol_failures_are_structured( + tmp_path: Path, + code: str, + expected_code: str | None, +) -> None: + handler = _handler(tmp_path, f"{sys.executable} -c {json.dumps(code)}") + + result = await run_command_handler(handler, b"{}", cwd=tmp_path) + + assert result.output is None + assert [item.code for item in result.diagnostics] == ( + [] if expected_code is None else [expected_code] + ) + + +async def test_runner_turns_exit_two_stderr_into_block(tmp_path: Path) -> None: + code = "import sys; print('protected', file=sys.stderr); raise SystemExit(2)" + handler = _handler(tmp_path, f"{sys.executable} -c {json.dumps(code)}") + + result = await run_command_handler(handler, b"{}", cwd=tmp_path) + + assert result.output == HookWireOutput(decision="block", reason="protected") + + +async def test_runner_times_out_and_reaps_process(tmp_path: Path) -> None: + code = "import time; time.sleep(10)" + handler = _handler( + tmp_path, + f"{sys.executable} -c {json.dumps(code)}", + timeout=0.01, + ) + + result = await run_command_handler(handler, b"{}", cwd=tmp_path) + + assert [item.code for item in result.diagnostics] == ["timeout"] + + +async def test_runner_reports_launch_failure_and_bounded_streams( + tmp_path: Path, +) -> None: + missing = _handler(tmp_path, "definitely-not-a-real-hook-command") + failed = await run_command_handler(missing, b"{}", cwd=tmp_path) + code = "import sys; print('x'*100); print('y'*100, file=sys.stderr)" + noisy = _handler(tmp_path, f"{sys.executable} -c {json.dumps(code)}") + bounded = await run_command_handler(noisy, b"{}", cwd=tmp_path, max_output_bytes=10) + + assert [item.code for item in failed.diagnostics] == ["launch_failed"] + assert {item.code for item in bounded.diagnostics} == { + "stdout_truncated", + "stderr_truncated", + "malformed_json", + } + + +def test_reducer_merges_session_context_and_common_fields(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + SessionStartEvent( + event=HookEvent.SESSION_START, cause=SessionStartCause.STARTUP + ), + ) + results = [ + HandlerResult( + handler_id="one", + output=HookWireOutput.model_validate( + { + "systemMessage": "notice", + "terminalSequence": "sequence", + "hookSpecificOutput": { + "hookEventName": "SessionStart", + "additionalContext": "context one", + }, + } + ), + ), + HandlerResult( + handler_id="two", + output=HookWireOutput.model_validate( + { + "continue": False, + "stopReason": "stop", + "hookSpecificOutput": { + "hookEventName": "SessionStart", + "additionalContext": "context two", + }, + } + ), + ), + ] + + decision = reduce_hook_results(invocation, results) + assert isinstance(decision, SessionStartDecision) + + assert decision.context == ["context one", "context two"] + assert decision.user_notices == ["notice"] + assert decision.terminal_sequences == ["sequence"] + assert decision.continue_processing is False + assert decision.stop_reason == "stop" + + +def test_reducer_permission_precedence_is_deny_ask_allow(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call", name="Bash", args={}), + ), + ) + results = [ + HandlerResult( + handler_id="allow", + output=HookWireOutput.model_validate( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "allow", + } + } + ), + ), + HandlerResult( + handler_id="ask", + output=HookWireOutput.model_validate( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "ask", + } + } + ), + ), + HandlerResult( + handler_id="deny", + output=HookWireOutput(decision="block", reason="no"), + ), + ] + + decision = reduce_hook_results(invocation, results) + assert isinstance(decision, PermissionRequestDecision | PreToolUseDecision) + + assert decision.permission.behavior == "deny" + assert decision.permission.reason == "no" + + +def test_reducer_covers_event_decision_shapes_and_loop_guards(tmp_path: Path) -> None: + agent = AgentIdentity(id="agent-1", name="researcher") + events_and_outputs = [ + ( + SessionEndEvent(event=HookEvent.SESSION_END, cause=SessionEndCause.OTHER), + {}, + ), + ( + NotificationEvent( + event=HookEvent.NOTIFICATION, + notification=DcodeNotification(type="agent_completed", message="Done"), + ), + {}, + ), + ( + PermissionRequestEvent( + event=HookEvent.PERMISSION_REQUEST, + call=ToolCallData(id="call", name="Bash", args={}), + ), + { + "hookSpecificOutput": { + "hookEventName": "PermissionRequest", + "decision": {"behavior": "deny", "message": "denied"}, + } + }, + ), + ( + PostToolUseEvent( + event=HookEvent.POST_TOOL_USE, + call=ToolCallData(id="call", name="Bash", args={}), + result=ToolMessage(content="done", tool_call_id="call"), + ), + { + "decision": "block", + "reason": "feedback", + "hookSpecificOutput": { + "hookEventName": "PostToolUse", + "additionalContext": "context", + }, + }, + ), + ( + StopEvent( + event=HookEvent.STOP, + continuation_count=1, + last_assistant_message="Done", + ), + { + "hookSpecificOutput": { + "hookEventName": "Stop", + "additionalContext": "continue", + } + }, + ), + ( + SubagentStartEvent(event=HookEvent.SUBAGENT_START, agent=agent), + { + "hookSpecificOutput": { + "hookEventName": "SubagentStart", + "additionalContext": "focus", + } + }, + ), + ( + SubagentStopEvent( + event=HookEvent.SUBAGENT_STOP, + agent=agent, + continuation_count=1, + last_assistant_message="Done", + ), + { + "hookSpecificOutput": { + "hookEventName": "SubagentStop", + "additionalContext": "continue", + } + }, + ), + ] + + decisions = [ + reduce_hook_results( + _invocation(tmp_path, event), + [ + HandlerResult( + handler_id="handler", + output=HookWireOutput.model_validate(output), + ) + ], + ) + for event, output in events_and_outputs + ] + + assert [decision.event for decision in decisions] == [ + HookEvent.SESSION_END, + HookEvent.NOTIFICATION, + HookEvent.PERMISSION_REQUEST, + HookEvent.POST_TOOL_USE, + HookEvent.STOP, + HookEvent.SUBAGENT_START, + HookEvent.SUBAGENT_STOP, + ] + permission = decisions[2] + post_tool = decisions[3] + stop = decisions[4] + subagent_start = decisions[5] + subagent_stop = decisions[6] + assert isinstance(permission, PermissionRequestDecision) + assert isinstance(post_tool, PostToolUseDecision) + assert isinstance(stop, StopDecision) + assert isinstance(subagent_start, SubagentStartDecision) + assert isinstance(subagent_stop, SubagentStopDecision) + assert permission.permission.behavior == "deny" + assert post_tool.feedback == ["feedback"] + assert post_tool.context == ["context"] + assert stop.continue_loop is False + assert subagent_start.context == ["focus"] + assert subagent_stop.context == [] + assert stop.diagnostics[0].code == "continuation_guard" + assert subagent_stop.diagnostics[0].code == "continuation_guard" + + +def test_reducer_guards_top_level_stop_blocks(tmp_path: Path) -> None: + stop_invocation = _invocation( + tmp_path, + StopEvent( + event=HookEvent.STOP, + continuation_count=1, + last_assistant_message="Done", + ), + ) + subagent_invocation = _invocation( + tmp_path, + SubagentStopEvent( + event=HookEvent.SUBAGENT_STOP, + agent=AgentIdentity(id="agent-1", name="researcher"), + continuation_count=1, + last_assistant_message="Done", + ), + ) + result = HandlerResult( + handler_id="block", + output=HookWireOutput(decision="block", reason="continue"), + ) + + stop = reduce_hook_results(stop_invocation, [result]) + subagent = reduce_hook_results(subagent_invocation, [result]) + + assert isinstance(stop, StopDecision) + assert isinstance(subagent, SubagentStopDecision) + assert stop.continue_loop is False + assert subagent.context == [] + assert stop.diagnostics[0].code == "continuation_guard" + assert subagent.diagnostics[0].code == "continuation_guard" + + +def test_reducer_retains_fail_open_diagnostics(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + NotificationEvent( + event=HookEvent.NOTIFICATION, + notification=DcodeNotification(type="agent_completed", message="Done"), + ), + ) + + decision = reduce_hook_results( + invocation, + [ + HandlerResult( + handler_id="broken", + diagnostics=( + HookDiagnostic( + code="timeout", + severity="warning", + message="timed out", + ), + ), + ) + ], + ) + + assert decision.continue_processing is True + assert decision.diagnostics[0].code == "timeout" + + +async def test_engine_runs_in_order_and_short_circuits(tmp_path: Path) -> None: + marker = tmp_path / "marker.txt" + first = ( + "import json,pathlib; " + f"pathlib.Path({str(marker)!r}).write_text('first'); " + "print(json.dumps({'continue': False}))" + ) + second = f"import pathlib; pathlib.Path({str(marker)!r}).write_text('second')" + snapshot = HooksSnapshot.from_config( + _config( + { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": f"{sys.executable} -c {json.dumps(first)}", + }, + { + "type": "command", + "command": f"{sys.executable} -c {json.dumps(second)}", + }, + ] + } + ] + } + ) + ) + invocation = _invocation( + tmp_path, + SessionStartEvent( + event=HookEvent.SESSION_START, cause=SessionStartCause.STARTUP + ), + ) + + decision = await HookEngine(snapshot).run(invocation) + + assert decision.continue_processing is False + assert marker.read_text() == "first" + + +async def test_engine_uses_captured_snapshot(tmp_path: Path) -> None: + original = _config( + { + "SessionStart": [ + {"hooks": [{"type": "command", "command": f"{sys.executable} -c pass"}]} + ] + } + ) + snapshot = HooksSnapshot.from_config(original) + original.hooks[HookEvent.SESSION_START][0].hooks[0].command = "missing" + invocation = _invocation( + tmp_path, + SessionStartEvent( + event=HookEvent.SESSION_START, cause=SessionStartCause.STARTUP + ), + ) + + decision = await HookEngine(snapshot).run(invocation) + + assert decision.diagnostics == [] + + +def test_legacy_dispatcher_remains_public() -> None: + assert callable(dispatch_hook) From 1bd7f11be39434e308cb0285836cfe044cb2e7e9 Mon Sep 17 00:00:00 2001 From: Johannes du Plessis <51395795+johannes117@users.noreply.github.com> Date: Tue, 21 Jul 2026 16:08:26 +0000 Subject: [PATCH 3/6] fix(code): isolate Hooks v2 imports and processes Keep legacy hook imports on the lightweight startup path and launch command handlers in separate process sessions. Co-authored-by: open-swe[bot] --- libs/code/deepagents_code/hooks/__init__.py | 4 +--- libs/code/deepagents_code/hooks/runner.py | 1 + .../code/tests/unit_tests/hooks/test_engine.py | 18 +++++++++++++++++- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/libs/code/deepagents_code/hooks/__init__.py b/libs/code/deepagents_code/hooks/__init__.py index 70d34bc0a45..502ea93819e 100644 --- a/libs/code/deepagents_code/hooks/__init__.py +++ b/libs/code/deepagents_code/hooks/__init__.py @@ -1,6 +1,5 @@ -"""Hook contracts, execution engine, and compatibility dispatch.""" +"""Hook contracts and compatibility dispatch.""" -from deepagents_code.hooks.engine import HookEngine from deepagents_code.hooks.legacy import ( HOOK_SUBPROCESS_TIMEOUT, HOOK_TOOL_OUTPUT_LIMIT, @@ -17,7 +16,6 @@ __all__ = [ "HOOK_SUBPROCESS_TIMEOUT", "HOOK_TOOL_OUTPUT_LIMIT", - "HookEngine", "_background_tasks", "dispatch_hook", "dispatch_hook_fire_and_forget", diff --git a/libs/code/deepagents_code/hooks/runner.py b/libs/code/deepagents_code/hooks/runner.py index e8d379196f8..0074d3dac51 100644 --- a/libs/code/deepagents_code/hooks/runner.py +++ b/libs/code/deepagents_code/hooks/runner.py @@ -74,6 +74,7 @@ async def run_command_handler( stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + start_new_session=True, ) except (OSError, ValueError) as exc: return _failure(handler.id, "launch_failed", f"Could not launch hook: {exc}") diff --git a/libs/code/tests/unit_tests/hooks/test_engine.py b/libs/code/tests/unit_tests/hooks/test_engine.py index a5b534819f2..ca0ab530884 100644 --- a/libs/code/tests/unit_tests/hooks/test_engine.py +++ b/libs/code/tests/unit_tests/hooks/test_engine.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import subprocess import sys from typing import TYPE_CHECKING from uuid import uuid4 @@ -12,7 +13,8 @@ from langgraph.types import Command from deepagents_code.approval_mode import ApprovalMode -from deepagents_code.hooks import HookEngine, dispatch_hook +from deepagents_code.hooks import dispatch_hook +from deepagents_code.hooks.engine import HookEngine from deepagents_code.hooks.models.adapters import HOOK_WIRE_INPUT_ADAPTER from deepagents_code.hooks.models.config import HooksConfig from deepagents_code.hooks.models.domain import ( @@ -761,3 +763,17 @@ async def test_engine_uses_captured_snapshot(tmp_path: Path) -> None: def test_legacy_dispatcher_remains_public() -> None: assert callable(dispatch_hook) + + +def test_legacy_package_import_does_not_load_engine() -> None: + code = ( + "import sys; import deepagents_code.hooks; " + "raise SystemExit('deepagents_code.hooks.engine' in sys.modules)" + ) + + result = subprocess.run( + [sys.executable, "-c", code], + check=False, + ) + + assert result.returncode == 0 From 01f731e7b475a70c2dd2199b2476f6c9dab3dfbb Mon Sep 17 00:00:00 2001 From: Johannes du Plessis Date: Tue, 21 Jul 2026 14:53:44 -0700 Subject: [PATCH 4/6] cr --- libs/code/deepagents_code/hooks/engine.py | 39 ++- libs/code/deepagents_code/hooks/projection.py | 16 +- libs/code/deepagents_code/hooks/reducer.py | 61 ++++- libs/code/deepagents_code/hooks/runner.py | 13 +- libs/code/deepagents_code/hooks/snapshot.py | 128 ++++++--- libs/code/deepagents_code/hooks/tools.py | 59 +++++ .../tests/unit_tests/hooks/test_engine.py | 246 ++++++++++++++++-- 7 files changed, 480 insertions(+), 82 deletions(-) create mode 100644 libs/code/deepagents_code/hooks/tools.py diff --git a/libs/code/deepagents_code/hooks/engine.py b/libs/code/deepagents_code/hooks/engine.py index 53f383d564d..95831211e5e 100644 --- a/libs/code/deepagents_code/hooks/engine.py +++ b/libs/code/deepagents_code/hooks/engine.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from dataclasses import dataclass from typing import TYPE_CHECKING @@ -11,7 +12,6 @@ from deepagents_code.hooks.runner import ( DEFAULT_HOOK_TIMEOUT, MAX_HOOK_OUTPUT_BYTES, - HandlerResult, run_command_handler, ) @@ -31,6 +31,10 @@ class HookEngine: async def run(self, invocation: HookInvocation) -> HookDecision: """Execute matching handlers and return a normalized decision. + Matching handlers run concurrently with independent timeouts. Results + are reduced in stable configuration order, independent of completion + order. + Args: invocation: Native lifecycle invocation. @@ -49,23 +53,30 @@ async def run(self, invocation: HookInvocation) -> HookDecision: return reduce_hook_results( invocation, (), - diagnostics=(*match.diagnostics, diagnostic), + diagnostics=( + *self.snapshot.diagnostics, + *match.diagnostics, + diagnostic, + ), ) - results: list[HandlerResult] = [] - for handler in match.handlers: - result = await run_command_handler( - handler, - payload, - cwd=invocation.context.cwd, - default_timeout=self.default_timeout, - max_output_bytes=self.max_output_bytes, + results = await asyncio.gather( + *( + run_command_handler( + handler, + payload, + cwd=invocation.context.cwd, + default_timeout=self.default_timeout, + max_output_bytes=self.max_output_bytes, + ) + for handler in match.handlers ) - results.append(result) - if result.output is not None and not result.output.continue_: - break + ) return reduce_hook_results( invocation, results, - diagnostics=match.diagnostics, + diagnostics=( + *self.snapshot.diagnostics, + *match.diagnostics, + ), ) diff --git a/libs/code/deepagents_code/hooks/projection.py b/libs/code/deepagents_code/hooks/projection.py index c7ad64ee7e0..824ddf4c844 100644 --- a/libs/code/deepagents_code/hooks/projection.py +++ b/libs/code/deepagents_code/hooks/projection.py @@ -36,6 +36,7 @@ WireNotificationType, WirePermissionMode, ) +from deepagents_code.hooks.tools import to_wire_call from deepagents_code.json_types import JSON_VALUE_ADAPTER, JsonValue if TYPE_CHECKING: @@ -85,11 +86,12 @@ def project_hook_input(invocation: HookInvocation) -> HookWireInput: reason=event.cause, ) elif isinstance(event, PermissionRequestEvent): + tool_name, tool_input = to_wire_call(event.call) result = PermissionRequestWireInput( **_common_fields(invocation), hook_event_name=HookEvent.PERMISSION_REQUEST, - tool_name=event.call.name, - tool_input=event.call.args, + tool_name=tool_name, + tool_input=tool_input, ) elif isinstance(event, NotificationEvent): result = NotificationWireInput( @@ -100,19 +102,21 @@ def project_hook_input(invocation: HookInvocation) -> HookWireInput: notification_type=_notification_type(event.notification.type), ) elif isinstance(event, PreToolUseEvent): + tool_name, tool_input = to_wire_call(event.call) result = PreToolUseWireInput( **_common_fields(invocation), hook_event_name=HookEvent.PRE_TOOL_USE, - tool_name=event.call.name, - tool_input=event.call.args, + tool_name=tool_name, + tool_input=tool_input, tool_use_id=event.call.id, ) elif isinstance(event, PostToolUseEvent): + tool_name, tool_input = to_wire_call(event.call) result = PostToolUseWireInput( **_common_fields(invocation), hook_event_name=HookEvent.POST_TOOL_USE, - tool_name=event.call.name, - tool_input=event.call.args, + tool_name=tool_name, + tool_input=tool_input, tool_response=_tool_result(event.result), tool_use_id=event.call.id, duration_ms=event.duration_ms, diff --git a/libs/code/deepagents_code/hooks/reducer.py b/libs/code/deepagents_code/hooks/reducer.py index 4219dcfb10c..adb9b25c289 100644 --- a/libs/code/deepagents_code/hooks/reducer.py +++ b/libs/code/deepagents_code/hooks/reducer.py @@ -23,6 +23,7 @@ SubagentStopEvent, ) from deepagents_code.hooks.models.wire import ( + PermissionAllow, PermissionRequestSpecificOutput, PostToolUseSpecificOutput, PreToolUseSpecificOutput, @@ -41,6 +42,16 @@ _PERMISSION_RANK = {"none": 0, "allow": 1, "ask": 2, "deny": 3} +# Exit 2 / decision:"block" cannot veto these lifecycle points in MVP. +_NON_BLOCKING_EVENTS = frozenset( + { + HookEvent.SESSION_START, + HookEvent.SESSION_END, + HookEvent.NOTIFICATION, + HookEvent.SUBAGENT_START, + } +) + @dataclass(slots=True) class _Reduction: @@ -97,7 +108,7 @@ def _merge_output( if output.terminal_sequence is not None: state.terminal_sequences.append(output.terminal_sequence) if output.decision == "block": - _merge_block(invocation, state, output.reason) + _merge_block(invocation, state, handler_id, output.reason) specific = output.hook_specific_output if specific is None: @@ -113,12 +124,13 @@ def _merge_output( ) ) return - _merge_specific(invocation, state, specific) + _merge_specific(invocation, state, handler_id, specific) def _merge_block( invocation: HookInvocation, state: _Reduction, + handler_id: str, reason: str | None, ) -> None: message = reason or "Blocked by hook" @@ -144,6 +156,19 @@ def _merge_block( state.diagnostics.append(_loop_guard_diagnostic()) else: state.context.append(message) + elif event in _NON_BLOCKING_EVENTS: + # Exit 2 / decision:"block" is not a veto for these events; keep going + # and surface the attempt so configs that expect Claude blocking see why + # dcode ignored it. + state.diagnostics.append( + HookDiagnostic( + code="unsupported_block", + severity="warning", + message=f"Block/exit 2 is not supported for {event.value}: {message}", + handler_id=handler_id, + field="decision", + ) + ) else: state.stop_reason = message state.continue_processing = False @@ -152,6 +177,7 @@ def _merge_block( def _merge_specific( invocation: HookInvocation, state: _Reduction, + handler_id: str, specific: object, ) -> None: if isinstance(specific, SessionStartSpecificOutput): @@ -159,6 +185,12 @@ def _merge_specific( elif isinstance(specific, PreToolUseSpecificOutput): _append(state.context, specific.additional_context) behavior = specific.permission_decision + if specific.updated_input is not None: + _diagnose_unsupported_updated_input(state, handler_id) + # Allow/ask coupled to mutation falls back to normal permission flow; + # deny remains safe without applying the mutated input. + if behavior in {"allow", "ask"}: + behavior = None if behavior is not None: normalized = "none" if behavior == "defer" else behavior _merge_permission( @@ -171,7 +203,13 @@ def _merge_specific( elif isinstance(specific, PermissionRequestSpecificOutput): decision = specific.decision if decision.behavior == "allow": - _merge_permission(state, PermissionEffect(behavior="allow")) + if ( + isinstance(decision, PermissionAllow) + and decision.updated_input is not None + ): + _diagnose_unsupported_updated_input(state, handler_id) + else: + _merge_permission(state, PermissionEffect(behavior="allow")) else: _merge_permission( state, @@ -208,6 +246,23 @@ def _merge_specific( state.context.append(specific.additional_context) +def _diagnose_unsupported_updated_input( + state: _Reduction, + handler_id: str, +) -> None: + state.diagnostics.append( + HookDiagnostic( + code="unsupported_field", + severity="warning", + message=( + "updatedInput is not supported; the mutated tool input was ignored" + ), + handler_id=handler_id, + field="updatedInput", + ) + ) + + def _merge_permission(state: _Reduction, effect: PermissionEffect) -> None: if _PERMISSION_RANK[effect.behavior] >= _PERMISSION_RANK[state.permission.behavior]: state.permission = effect diff --git a/libs/code/deepagents_code/hooks/runner.py b/libs/code/deepagents_code/hooks/runner.py index 0074d3dac51..144f8f1e14e 100644 --- a/libs/code/deepagents_code/hooks/runner.py +++ b/libs/code/deepagents_code/hooks/runner.py @@ -5,7 +5,6 @@ import asyncio import json import os -import shlex from dataclasses import dataclass from typing import TYPE_CHECKING @@ -59,16 +58,14 @@ async def run_command_handler( Raises: asyncio.CancelledError: If the caller cancels command execution. """ - try: - argv = shlex.split(handler.command) - except ValueError as exc: - return _failure(handler.id, "invalid_command", f"Invalid hook command: {exc}") - if not argv: + if not handler.command.strip(): return _failure(handler.id, "invalid_command", "Hook command is empty") try: - process = await asyncio.create_subprocess_exec( - *argv, + # Shell form preserves pipes, redirects, globs, and $VAR expansion to + # match the compatible command-hook contract (no separate args field). + process = await asyncio.create_subprocess_shell( + handler.command, cwd=cwd, env=os.environ.copy(), stdin=asyncio.subprocess.PIPE, diff --git a/libs/code/deepagents_code/hooks/snapshot.py b/libs/code/deepagents_code/hooks/snapshot.py index 61b68fff580..f4bb02b1ca2 100644 --- a/libs/code/deepagents_code/hooks/snapshot.py +++ b/libs/code/deepagents_code/hooks/snapshot.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging import re from dataclasses import dataclass from types import MappingProxyType @@ -14,7 +15,12 @@ PermissionRequestEvent, PostToolUseEvent, PreToolUseEvent, + SessionEndEvent, + SessionStartEvent, + SubagentStartEvent, + SubagentStopEvent, ) +from deepagents_code.hooks.tools import to_wire_tool_name if TYPE_CHECKING: from collections.abc import Mapping @@ -23,15 +29,25 @@ from deepagents_code.hooks.models.config import HooksConfig from deepagents_code.hooks.models.domain import HookInvocation +logger = logging.getLogger(__name__) + +# Events whose matcher filters a field on the invocation. `Stop` has no matcher. _MATCHABLE_EVENTS = frozenset( { + HookEvent.SESSION_START, + HookEvent.SESSION_END, HookEvent.PERMISSION_REQUEST, HookEvent.NOTIFICATION, HookEvent.PRE_TOOL_USE, HookEvent.POST_TOOL_USE, + HookEvent.SUBAGENT_START, + HookEvent.SUBAGENT_STOP, } ) +# Claude-compatible exact-match character set (letters, digits, _, -, spaces, ,, |). +_EXACT_MATCHER = re.compile(r"^[\w\s,\-|]+$") + @dataclass(frozen=True, slots=True) class HookHandler: @@ -42,17 +58,16 @@ class HookHandler: command: str timeout: float | None status_message: str | None - matcher: Pattern[str] | None + matcher: Pattern[str] | frozenset[str] | None matcher_text: str | None - matcher_error: str | None = None @dataclass(frozen=True, slots=True) class HookMatch: - """Matched handlers and configuration diagnostics for one invocation.""" + """Matched handlers for one invocation.""" handlers: tuple[HookHandler, ...] - diagnostics: tuple[HookDiagnostic, ...] + diagnostics: tuple[HookDiagnostic, ...] = () @dataclass(frozen=True, slots=True) @@ -60,11 +75,15 @@ class HooksSnapshot: """Immutable, declaration-ordered Hooks v2 runtime configuration.""" handlers: Mapping[HookEvent, tuple[HookHandler, ...]] + diagnostics: tuple[HookDiagnostic, ...] = () @classmethod def from_config(cls, config: HooksConfig) -> HooksSnapshot: """Build an immutable runtime snapshot from validated configuration. + Invalid matcher groups are rejected at compile time with a warning + diagnostic; their handlers are never added to the snapshot. + Args: config: Validated Hooks v2 configuration. @@ -72,10 +91,25 @@ def from_config(cls, config: HooksConfig) -> HooksSnapshot: A snapshot whose handler order and matchers cannot change in flight. """ expanded: dict[HookEvent, tuple[HookHandler, ...]] = {} + diagnostics: list[HookDiagnostic] = [] for event, groups in config.hooks.items(): handlers: list[HookHandler] = [] for group_index, group in enumerate(groups): matcher, error = _compile_matcher(group.matcher) + if error is not None: + message = ( + f"Rejected hook group {event.value}:{group_index}: {error}" + ) + logger.warning(message) + diagnostics.append( + HookDiagnostic( + code="invalid_matcher", + severity="warning", + message=message, + field="matcher", + ) + ) + continue for handler_index, spec in enumerate(group.hooks): handlers.append( HookHandler( @@ -86,11 +120,13 @@ def from_config(cls, config: HooksConfig) -> HooksSnapshot: status_message=spec.status_message, matcher=matcher, matcher_text=group.matcher, - matcher_error=error, ) ) expanded[event] = tuple(handlers) - return cls(handlers=MappingProxyType(expanded)) + return cls( + handlers=MappingProxyType(expanded), + diagnostics=tuple(diagnostics), + ) def match(self, invocation: HookInvocation) -> HookMatch: """Return handlers matching an invocation in declaration order. @@ -99,49 +135,75 @@ def match(self, invocation: HookInvocation) -> HookMatch: invocation: Domain invocation to match. Returns: - Matching handlers and diagnostics for invalid configured matchers. + Matching handlers. Matcher compile failures are reported on the + snapshot itself, not per invocation. """ event = invocation.event.event target = _match_target(invocation) - matched: list[HookHandler] = [] - diagnostics: list[HookDiagnostic] = [] - for handler in self.handlers.get(event, ()): - if handler.matcher_error is not None: - diagnostics.append( - HookDiagnostic( - code="invalid_matcher", - severity="warning", - message=handler.matcher_error, - handler_id=handler.id, - field="matcher", - ) - ) - continue - if ( - event not in _MATCHABLE_EVENTS - or handler.matcher is None - or (target is not None and handler.matcher.search(target) is not None) - ): - matched.append(handler) - return HookMatch(handlers=tuple(matched), diagnostics=tuple(diagnostics)) - - -def _compile_matcher(value: str | None) -> tuple[Pattern[str] | None, str | None]: - if not value: + matched = tuple( + handler + for handler in self.handlers.get(event, ()) + if _handler_matches(handler, event, target) + ) + return HookMatch(handlers=matched) + + +def _compile_matcher( + value: str | None, +) -> tuple[Pattern[str] | frozenset[str] | None, str | None]: + """Compile a Claude-compatible matcher pattern. + + Omitted, empty, or `*` matches all. Exact-character matchers use exact + string equality (with `|` / `,` alternation). Any other character switches + to an unanchored regular expression. + + Args: + value: Raw matcher string from configuration. + + Returns: + `(matcher, error)` where `matcher` is `None` for match-all, a frozenset + for exact names, or a compiled regex; `error` is set when compilation + fails. + """ + if not value or value == "*": return None, None + if _EXACT_MATCHER.fullmatch(value): + names = frozenset( + part.strip() for part in re.split(r"[|,]", value) if part.strip() + ) + return names, None try: return re.compile(value), None except re.error as exc: return None, f"Invalid hook matcher {value!r}: {exc}" +def _handler_matches( + handler: HookHandler, + event: HookEvent, + target: str | None, +) -> bool: + if event not in _MATCHABLE_EVENTS or handler.matcher is None: + return True + if target is None: + return False + matcher = handler.matcher + if isinstance(matcher, frozenset): + return target in matcher + return matcher.search(target) is not None + + def _match_target(invocation: HookInvocation) -> str | None: event = invocation.event if isinstance( event, PermissionRequestEvent | PreToolUseEvent | PostToolUseEvent, ): - return event.call.name + return to_wire_tool_name(event.call.name) if isinstance(event, NotificationEvent): return event.notification.type + if isinstance(event, SessionStartEvent | SessionEndEvent): + return event.cause.value + if isinstance(event, SubagentStartEvent | SubagentStopEvent): + return event.agent.name return None diff --git a/libs/code/deepagents_code/hooks/tools.py b/libs/code/deepagents_code/hooks/tools.py new file mode 100644 index 00000000000..74bfda54783 --- /dev/null +++ b/libs/code/deepagents_code/hooks/tools.py @@ -0,0 +1,59 @@ +"""Native dcode tool vocabulary mapped to compatible wire names.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from deepagents_code.hooks.models.domain import ToolCallData + from deepagents_code.json_types import JsonObject + +_NATIVE_TO_WIRE_NAME: dict[str, str] = { + "execute": "Bash", + "write_file": "Write", + "edit_file": "Edit", + "read_file": "Read", + "glob": "Glob", + "grep": "Grep", + "ls": "LS", +} + + +def to_wire_tool_name(name: str) -> str: + """Map a native tool name to the compatible wire tool name. + + Args: + name: Native dcode or already-compatible tool name. + + Returns: + The Claude-compatible tool name used for matchers and wire payloads. + """ + if name in _NATIVE_TO_WIRE_NAME: + return _NATIVE_TO_WIRE_NAME[name] + return name + + +def to_wire_tool_input(name: str, args: JsonObject) -> JsonObject: + """Map native tool arguments to the compatible wire input object. + + Args: + name: Native dcode tool name (before wire renaming). + args: Native tool-call arguments. + + Returns: + JSON object suitable for `tool_input` on the wire. + """ + del name + return args + + +def to_wire_call(call: ToolCallData) -> tuple[str, JsonObject]: + """Project a native tool call into compatible wire name and input. + + Args: + call: Native tool-call data from a lifecycle owner. + + Returns: + `(tool_name, tool_input)` for matchers and wire projection. + """ + return to_wire_tool_name(call.name), to_wire_tool_input(call.name, call.args) diff --git a/libs/code/tests/unit_tests/hooks/test_engine.py b/libs/code/tests/unit_tests/hooks/test_engine.py index ca0ab530884..70b1c1288e1 100644 --- a/libs/code/tests/unit_tests/hooks/test_engine.py +++ b/libs/code/tests/unit_tests/hooks/test_engine.py @@ -189,9 +189,72 @@ def test_snapshot_matches_notification_and_skips_tool_mismatch(tmp_path: Path) - assert snapshot.match(permission).handlers == () -def test_snapshot_reports_invalid_regex_and_runs_non_matchable_groups( - tmp_path: Path, -) -> None: +def test_snapshot_matches_native_tool_names_via_wire_adapter(tmp_path: Path) -> None: + snapshot = HooksSnapshot.from_config( + _config( + { + "PreToolUse": [ + { + "matcher": "Bash|Write", + "hooks": [{"type": "command", "command": "policy"}], + } + ] + } + ) + ) + execute = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call-1", name="execute", args={"command": "pwd"}), + ), + ) + write = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call-2", name="write_file", args={}), + ), + ) + read = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call-3", name="read_file", args={}), + ), + ) + + assert [item.command for item in snapshot.match(execute).handlers] == ["policy"] + assert [item.command for item in snapshot.match(write).handlers] == ["policy"] + assert snapshot.match(read).handlers == () + + +def test_snapshot_exact_matcher_does_not_substring_match(tmp_path: Path) -> None: + snapshot = HooksSnapshot.from_config( + _config( + { + "PreToolUse": [ + { + "matcher": "Write", + "hooks": [{"type": "command", "command": "write"}], + } + ] + } + ) + ) + # Exact matchers must not treat "Write" as a regex substring of "WriteFile". + invocation = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call-1", name="WriteFile", args={}), + ), + ) + + assert snapshot.match(invocation).handlers == () + + +def test_snapshot_rejects_invalid_matcher_at_compile_time(tmp_path: Path) -> None: snapshot = HooksSnapshot.from_config( _config( { @@ -201,9 +264,12 @@ def test_snapshot_reports_invalid_regex_and_runs_non_matchable_groups( "hooks": [{"type": "command", "command": "bad"}], }, { - "matcher": "ignored", + "matcher": "logout", "hooks": [{"type": "command", "command": "good"}], }, + { + "hooks": [{"type": "command", "command": "all"}], + }, ] } ) @@ -215,8 +281,11 @@ def test_snapshot_reports_invalid_regex_and_runs_non_matchable_groups( match = snapshot.match(invocation) - assert [handler.command for handler in match.handlers] == ["good"] - assert [diagnostic.code for diagnostic in match.diagnostics] == ["invalid_matcher"] + assert [handler.command for handler in match.handlers] == ["all"] + assert [diagnostic.code for diagnostic in snapshot.diagnostics] == [ + "invalid_matcher" + ] + assert match.diagnostics == () @pytest.mark.parametrize( @@ -316,7 +385,29 @@ def test_projects_all_wire_events( assert payload["transcript_path"].endswith("thread-1.jsonl") -def test_serializes_native_command_as_json(tmp_path: Path) -> None: +def test_projects_native_tool_names_to_wire(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData( + id="call-1", + name="execute", + args={"command": "pwd"}, + ), + ), + ) + + payload = HOOK_WIRE_INPUT_ADAPTER.dump_python( + project_hook_input(invocation), + mode="json", + by_alias=True, + exclude_none=True, + ) + + assert payload["tool_name"] == "Bash" + assert payload["tool_input"] == {"command": "pwd"} + invocation = _invocation( tmp_path, PostToolUseEvent.model_construct( @@ -361,6 +452,18 @@ async def test_runner_accepts_json_and_uses_invocation_cwd(tmp_path: Path) -> No assert result.diagnostics == () +async def test_runner_executes_shell_syntax(tmp_path: Path) -> None: + out = tmp_path / "shell.txt" + command = f"printf '%s' '{{\"systemMessage\":\"ok\"}}' > {out} && cat {out}" + handler = _handler(tmp_path, command) + + result = await run_command_handler(handler, b"{}", cwd=tmp_path) + + assert result.output is not None + assert result.output.system_message == "ok" + assert out.read_text() == '{"systemMessage":"ok"}' + + @pytest.mark.parametrize( ("code", "expected_code"), [ @@ -410,13 +513,18 @@ async def test_runner_times_out_and_reaps_process(tmp_path: Path) -> None: async def test_runner_reports_launch_failure_and_bounded_streams( tmp_path: Path, ) -> None: + # Shell form: a missing binary is started by the shell and exits non-zero + # rather than failing at process spawn. missing = _handler(tmp_path, "definitely-not-a-real-hook-command") failed = await run_command_handler(missing, b"{}", cwd=tmp_path) + empty = _handler(tmp_path, " ") + empty_result = await run_command_handler(empty, b"{}", cwd=tmp_path) code = "import sys; print('x'*100); print('y'*100, file=sys.stderr)" noisy = _handler(tmp_path, f"{sys.executable} -c {json.dumps(code)}") bounded = await run_command_handler(noisy, b"{}", cwd=tmp_path, max_output_bytes=10) - assert [item.code for item in failed.diagnostics] == ["launch_failed"] + assert [item.code for item in failed.diagnostics] == ["nonzero_exit"] + assert [item.code for item in empty_result.diagnostics] == ["invalid_command"] assert {item.code for item in bounded.diagnostics} == { "stdout_truncated", "stderr_truncated", @@ -698,14 +806,110 @@ def test_reducer_retains_fail_open_diagnostics(tmp_path: Path) -> None: assert decision.diagnostics[0].code == "timeout" -async def test_engine_runs_in_order_and_short_circuits(tmp_path: Path) -> None: - marker = tmp_path / "marker.txt" - first = ( - "import json,pathlib; " - f"pathlib.Path({str(marker)!r}).write_text('first'); " - "print(json.dumps({'continue': False}))" +def test_reducer_ignores_session_start_block(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + SessionStartEvent( + event=HookEvent.SESSION_START, cause=SessionStartCause.STARTUP + ), + ) + + decision = reduce_hook_results( + invocation, + [ + HandlerResult( + handler_id="block", + output=HookWireOutput(decision="block", reason="nope"), + ) + ], + ) + assert isinstance(decision, SessionStartDecision) + + assert decision.continue_processing is True + assert decision.diagnostics[0].code == "unsupported_block" + + +def test_reducer_warns_on_unsupported_updated_input(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call", name="execute", args={}), + ), + ) + + decision = reduce_hook_results( + invocation, + [ + HandlerResult( + handler_id="mutate", + output=HookWireOutput.model_validate( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "allow", + "updatedInput": {"command": "echo mutated"}, + } + } + ), + ) + ], + ) + assert isinstance(decision, PreToolUseDecision) + + assert decision.permission.behavior == "none" + assert decision.diagnostics[0].code == "unsupported_field" + assert decision.diagnostics[0].field == "updatedInput" + + +def test_reducer_honors_deny_even_with_updated_input(tmp_path: Path) -> None: + invocation = _invocation( + tmp_path, + PreToolUseEvent( + event=HookEvent.PRE_TOOL_USE, + call=ToolCallData(id="call", name="execute", args={}), + ), + ) + + decision = reduce_hook_results( + invocation, + [ + HandlerResult( + handler_id="deny", + output=HookWireOutput.model_validate( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": "blocked", + "updatedInput": {"command": "echo mutated"}, + } + } + ), + ) + ], + ) + assert isinstance(decision, PreToolUseDecision) + + assert decision.permission.behavior == "deny" + assert decision.permission.reason == "blocked" + assert decision.diagnostics[0].code == "unsupported_field" + + +async def test_engine_runs_handlers_concurrently(tmp_path: Path) -> None: + first = tmp_path / "first.txt" + second = tmp_path / "second.txt" + first_cmd = ( + "import json,pathlib,time; " + "time.sleep(0.05); " + f"pathlib.Path({str(first)!r}).write_text('first'); " + "print(json.dumps({'continue': False, 'stopReason': 'stop'}))" + ) + second_cmd = ( + "import pathlib,time; " + "time.sleep(0.05); " + f"pathlib.Path({str(second)!r}).write_text('second')" ) - second = f"import pathlib; pathlib.Path({str(marker)!r}).write_text('second')" snapshot = HooksSnapshot.from_config( _config( { @@ -714,11 +918,15 @@ async def test_engine_runs_in_order_and_short_circuits(tmp_path: Path) -> None: "hooks": [ { "type": "command", - "command": f"{sys.executable} -c {json.dumps(first)}", + "command": ( + f"{sys.executable} -c {json.dumps(first_cmd)}" + ), }, { "type": "command", - "command": f"{sys.executable} -c {json.dumps(second)}", + "command": ( + f"{sys.executable} -c {json.dumps(second_cmd)}" + ), }, ] } @@ -736,7 +944,9 @@ async def test_engine_runs_in_order_and_short_circuits(tmp_path: Path) -> None: decision = await HookEngine(snapshot).run(invocation) assert decision.continue_processing is False - assert marker.read_text() == "first" + assert decision.stop_reason == "stop" + assert first.read_text() == "first" + assert second.read_text() == "second" async def test_engine_uses_captured_snapshot(tmp_path: Path) -> None: From 73dafc63d2c234d1e9ca4de090250726ee8ce881 Mon Sep 17 00:00:00 2001 From: Johannes du Plessis Date: Tue, 21 Jul 2026 15:05:22 -0700 Subject: [PATCH 5/6] cr --- libs/code/deepagents_code/hooks/tools.py | 83 ++++++++++++++++--- .../tests/unit_tests/hooks/test_engine.py | 78 +++++++++++++++++ 2 files changed, 148 insertions(+), 13 deletions(-) diff --git a/libs/code/deepagents_code/hooks/tools.py b/libs/code/deepagents_code/hooks/tools.py index 74bfda54783..c7911fabc03 100644 --- a/libs/code/deepagents_code/hooks/tools.py +++ b/libs/code/deepagents_code/hooks/tools.py @@ -2,20 +2,78 @@ from __future__ import annotations +import re from typing import TYPE_CHECKING if TYPE_CHECKING: + from collections.abc import Callable + from deepagents_code.hooks.models.domain import ToolCallData from deepagents_code.json_types import JsonObject -_NATIVE_TO_WIRE_NAME: dict[str, str] = { - "execute": "Bash", - "write_file": "Write", - "edit_file": "Edit", - "read_file": "Read", - "glob": "Glob", - "grep": "Grep", - "ls": "LS", + +def _select(args: JsonObject, *fields: str) -> JsonObject: + return {field: args[field] for field in fields if field in args} + + +def _bash_input(args: JsonObject) -> JsonObject: + result = _select(args, "command") + if "timeout" in args: + timeout = args["timeout"] + result["timeout"] = ( + timeout * 1000 + if isinstance(timeout, int) and not isinstance(timeout, bool) + else timeout + ) + return result + + +def _write_input(args: JsonObject) -> JsonObject: + return _select(args, "file_path", "content") + + +def _edit_input(args: JsonObject) -> JsonObject: + return _select(args, "file_path", "old_string", "new_string", "replace_all") + + +def _read_input(args: JsonObject) -> JsonObject: + result = _select(args, "file_path", "limit") + if "offset" in args: + offset = args["offset"] + result["offset"] = ( + offset + 1 + if isinstance(offset, int) and not isinstance(offset, bool) + else offset + ) + return result + + +def _glob_input(args: JsonObject) -> JsonObject: + return _select(args, "pattern", "path") + + +def _grep_input(args: JsonObject) -> JsonObject: + result = _select(args, "path", "glob", "output_mode") + if "pattern" in args: + pattern = args["pattern"] + result["pattern"] = re.escape(pattern) if isinstance(pattern, str) else pattern + if "max_count" in args: + result["head_limit"] = args["max_count"] + return result + + +def _ls_input(args: JsonObject) -> JsonObject: + return _select(args, "path") + + +_NATIVE_TO_WIRE: dict[str, tuple[str, Callable[[JsonObject], JsonObject]]] = { + "execute": ("Bash", _bash_input), + "write_file": ("Write", _write_input), + "edit_file": ("Edit", _edit_input), + "read_file": ("Read", _read_input), + "glob": ("Glob", _glob_input), + "grep": ("Grep", _grep_input), + "ls": ("LS", _ls_input), } @@ -28,9 +86,8 @@ def to_wire_tool_name(name: str) -> str: Returns: The Claude-compatible tool name used for matchers and wire payloads. """ - if name in _NATIVE_TO_WIRE_NAME: - return _NATIVE_TO_WIRE_NAME[name] - return name + adapter = _NATIVE_TO_WIRE.get(name) + return adapter[0] if adapter is not None else name def to_wire_tool_input(name: str, args: JsonObject) -> JsonObject: @@ -43,8 +100,8 @@ def to_wire_tool_input(name: str, args: JsonObject) -> JsonObject: Returns: JSON object suitable for `tool_input` on the wire. """ - del name - return args + adapter = _NATIVE_TO_WIRE.get(name) + return adapter[1](args) if adapter is not None else args def to_wire_call(call: ToolCallData) -> tuple[str, JsonObject]: diff --git a/libs/code/tests/unit_tests/hooks/test_engine.py b/libs/code/tests/unit_tests/hooks/test_engine.py index 70b1c1288e1..3cc66295318 100644 --- a/libs/code/tests/unit_tests/hooks/test_engine.py +++ b/libs/code/tests/unit_tests/hooks/test_engine.py @@ -49,11 +49,13 @@ from deepagents_code.hooks.reducer import reduce_hook_results from deepagents_code.hooks.runner import HandlerResult, run_command_handler from deepagents_code.hooks.snapshot import HookHandler, HooksSnapshot +from deepagents_code.hooks.tools import to_wire_call if TYPE_CHECKING: from pathlib import Path from deepagents_code.hooks.models.domain import HookDomainEvent + from deepagents_code.json_types import JsonObject def _context(tmp_path: Path, *, agent: AgentIdentity | None = None) -> HookContext: @@ -423,6 +425,82 @@ def test_projects_native_tool_names_to_wire(tmp_path: Path) -> None: assert payload["tool_response"]["goto"] == [] +@pytest.mark.parametrize( + ("name", "args", "wire_name", "wire_input"), + [ + ( + "execute", + {"command": "pytest", "timeout": 30}, + "Bash", + {"command": "pytest", "timeout": 30_000}, + ), + ( + "write_file", + {"file_path": "/tmp/result.txt", "content": "done"}, + "Write", + {"file_path": "/tmp/result.txt", "content": "done"}, + ), + ( + "edit_file", + { + "file_path": "/tmp/result.txt", + "old_string": "before", + "new_string": "after", + "replace_all": True, + }, + "Edit", + { + "file_path": "/tmp/result.txt", + "old_string": "before", + "new_string": "after", + "replace_all": True, + }, + ), + ( + "read_file", + {"file_path": "/tmp/result.txt", "offset": 0, "limit": 100}, + "Read", + {"file_path": "/tmp/result.txt", "offset": 1, "limit": 100}, + ), + ( + "glob", + {"pattern": "**/*.py", "path": "/tmp"}, + "Glob", + {"pattern": "**/*.py", "path": "/tmp"}, + ), + ( + "grep", + { + "pattern": "result.*", + "path": "/tmp", + "glob": "*.txt", + "output_mode": "content", + "max_count": 20, + }, + "Grep", + { + "pattern": r"result\.\*", + "path": "/tmp", + "glob": "*.txt", + "output_mode": "content", + "head_limit": 20, + }, + ), + ("ls", {"path": "/tmp"}, "LS", {"path": "/tmp"}), + ("custom", {"value": 1}, "custom", {"value": 1}), + ], +) +def test_adapts_native_tool_calls_to_wire( + name: str, + args: JsonObject, + wire_name: str, + wire_input: JsonObject, +) -> None: + call = ToolCallData(id="call-1", name=name, args=args) + + assert to_wire_call(call) == (wire_name, wire_input) + + def test_serializes_native_tool_message_as_json(tmp_path: Path) -> None: invocation = _invocation( tmp_path, From 5528f768585015eacd816efd0f588d5e675ad83d Mon Sep 17 00:00:00 2001 From: Johannes du Plessis <51395795+johannes117@users.noreply.github.com> Date: Tue, 21 Jul 2026 22:23:18 +0000 Subject: [PATCH 6/6] fix(code): preserve hook exit status after closed stdin Co-authored-by: open-swe[bot] --- libs/code/deepagents_code/hooks/runner.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libs/code/deepagents_code/hooks/runner.py b/libs/code/deepagents_code/hooks/runner.py index 144f8f1e14e..f4cb921dd54 100644 --- a/libs/code/deepagents_code/hooks/runner.py +++ b/libs/code/deepagents_code/hooks/runner.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import contextlib import json import os from dataclasses import dataclass @@ -172,7 +173,8 @@ async def _communicate_bounded( try: await process.wait() stdout, stderr = await asyncio.gather(stdout_task, stderr_task) - await stdin_task + with contextlib.suppress(BrokenPipeError, ConnectionResetError): + await stdin_task except BaseException: stdin_task.cancel() stdout_task.cancel()