diff --git a/libs/code/deepagents_code/hooks/engine.py b/libs/code/deepagents_code/hooks/engine.py new file mode 100644 index 00000000000..95831211e5e --- /dev/null +++ b/libs/code/deepagents_code/hooks/engine.py @@ -0,0 +1,82 @@ +"""Standalone orchestration for the Hooks v2 execution engine.""" + +from __future__ import annotations + +import asyncio +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, + 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. + + Matching handlers run concurrently with independent timeouts. Results + are reduced in stable configuration order, independent of completion + order. + + 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=( + *self.snapshot.diagnostics, + *match.diagnostics, + diagnostic, + ), + ) + + 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 + ) + ) + return reduce_hook_results( + invocation, + results, + diagnostics=( + *self.snapshot.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..824ddf4c844 --- /dev/null +++ b/libs/code/deepagents_code/hooks/projection.py @@ -0,0 +1,229 @@ +"""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.hooks.tools import to_wire_call +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): + tool_name, tool_input = to_wire_call(event.call) + result = PermissionRequestWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.PERMISSION_REQUEST, + tool_name=tool_name, + tool_input=tool_input, + ) + 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): + tool_name, tool_input = to_wire_call(event.call) + result = PreToolUseWireInput( + **_common_fields(invocation), + hook_event_name=HookEvent.PRE_TOOL_USE, + 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=tool_name, + tool_input=tool_input, + 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..adb9b25c289 --- /dev/null +++ b/libs/code/deepagents_code/hooks/reducer.py @@ -0,0 +1,331 @@ +"""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 ( + PermissionAllow, + 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} + +# 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: + 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, handler_id, 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, handler_id, specific) + + +def _merge_block( + invocation: HookInvocation, + state: _Reduction, + handler_id: str, + 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) + 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 + + +def _merge_specific( + invocation: HookInvocation, + state: _Reduction, + handler_id: str, + 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 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( + state, + PermissionEffect( + behavior=normalized, + reason=specific.permission_decision_reason, + ), + ) + elif isinstance(specific, PermissionRequestSpecificOutput): + decision = specific.decision + if decision.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, + 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 _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 + + +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..f4cb921dd54 --- /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 contextlib +import json +import os +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. + """ + if not handler.command.strip(): + return _failure(handler.id, "invalid_command", "Hook command is empty") + + try: + # 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, + 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}") + + 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) + with contextlib.suppress(BrokenPipeError, ConnectionResetError): + 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..f4bb02b1ca2 --- /dev/null +++ b/libs/code/deepagents_code/hooks/snapshot.py @@ -0,0 +1,209 @@ +"""Immutable runtime snapshots for Hooks v2 configuration.""" + +from __future__ import annotations + +import logging +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, + SessionEndEvent, + SessionStartEvent, + SubagentStartEvent, + SubagentStopEvent, +) +from deepagents_code.hooks.tools import to_wire_tool_name + +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 + +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: + """One ordered command handler in a configuration snapshot.""" + + id: str + event: HookEvent + command: str + timeout: float | None + status_message: str | None + matcher: Pattern[str] | frozenset[str] | None + matcher_text: str | None + + +@dataclass(frozen=True, slots=True) +class HookMatch: + """Matched handlers 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, ...]] + 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. + + Returns: + 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( + 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, + ) + ) + expanded[event] = tuple(handlers) + return cls( + handlers=MappingProxyType(expanded), + diagnostics=tuple(diagnostics), + ) + + def match(self, invocation: HookInvocation) -> HookMatch: + """Return handlers matching an invocation in declaration order. + + Args: + invocation: Domain invocation to match. + + Returns: + Matching handlers. Matcher compile failures are reported on the + snapshot itself, not per invocation. + """ + event = invocation.event.event + target = _match_target(invocation) + 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 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..c7911fabc03 --- /dev/null +++ b/libs/code/deepagents_code/hooks/tools.py @@ -0,0 +1,116 @@ +"""Native dcode tool vocabulary mapped to compatible wire names.""" + +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 + + +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), +} + + +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. + """ + 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: + """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. + """ + 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]: + """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 new file mode 100644 index 00000000000..3cc66295318 --- /dev/null +++ b/libs/code/tests/unit_tests/hooks/test_engine.py @@ -0,0 +1,1067 @@ +"""Unit tests for the Hooks v2 execution engine.""" + +from __future__ import annotations + +import json +import subprocess +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 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 ( + 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 +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: + 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_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( + { + "SessionEnd": [ + { + "matcher": "[", + "hooks": [{"type": "command", "command": "bad"}], + }, + { + "matcher": "logout", + "hooks": [{"type": "command", "command": "good"}], + }, + { + "hooks": [{"type": "command", "command": "all"}], + }, + ] + } + ) + ) + invocation = _invocation( + tmp_path, + SessionEndEvent(event=HookEvent.SESSION_END, cause=SessionEndCause.OTHER), + ) + + match = snapshot.match(invocation) + + 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( + ("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_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( + 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"] == [] + + +@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, + 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 == () + + +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"), + [ + ("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: + # 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] == ["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", + "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" + + +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')" + ) + snapshot = HooksSnapshot.from_config( + _config( + { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": ( + f"{sys.executable} -c {json.dumps(first_cmd)}" + ), + }, + { + "type": "command", + "command": ( + f"{sys.executable} -c {json.dumps(second_cmd)}" + ), + }, + ] + } + ] + } + ) + ) + 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 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: + 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) + + +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