Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
e286b4b
fix: send hook_config to server in RemoteConversation
xingyaoww Feb 18, 2026
80ba8c6
test: add test for hook_config being sent to server
xingyaoww Feb 18, 2026
a790935
feat: Add HookExecutionEvent for hook observability
xingyaoww Feb 18, 2026
8acdc2f
Update examples/02_remote_agent_server/01_convo_with_local_agent_serv…
xingyaoww Feb 18, 2026
16caa43
Apply suggestion from @xingyaoww
xingyaoww Feb 18, 2026
a8eae38
feat: Add hook_config to ConversationState and SystemPromptEvent
xingyaoww Feb 18, 2026
2444bd1
test: add stop hook and verify HookExecutionEvent for both hooks
openhands-agent Feb 19, 2026
9990f4e
Merge branch 'main' into fix/remote-conversation-hook-config
xingyaoww Mar 2, 2026
ecacb88
fix: avoid circular import when rebuilding SystemPromptEvent
openhands-agent Mar 2, 2026
008a9d7
fix: truncate HookExecutionEvent logs to 50k chars
openhands-agent Mar 2, 2026
988b89b
docs: fix RemoteConversation PostToolUse hook comment
openhands-agent Mar 2, 2026
071702b
test: update example to demonstrate on_stop hook with syntax validation
xingyaoww Mar 2, 2026
69f37a7
test: fix agent instruction to demonstrate full on_stop hook cycle
xingyaoww Mar 2, 2026
fd8a2af
Merge main into fix/remote-conversation-hook-config
xingyaoww Mar 6, 2026
32c781e
Add example run log after merge from main
xingyaoww Mar 6, 2026
4c14b6e
Add JSON mode example run log
xingyaoww Mar 6, 2026
cfc7445
Rename pre_commit_check.sh to pycompile_check.sh
xingyaoww Mar 6, 2026
70ebee0
Remove old log files from .pr folder
xingyaoww Mar 6, 2026
ce7f1e9
Merge branch 'main' into fix/remote-conversation-hook-config
xingyaoww Mar 9, 2026
e346ea2
fix: make all hooks server-only in RemoteConversation
openhands-agent Mar 9, 2026
ee3a7c0
refactor: remove hook_config from SystemPromptEvent
openhands-agent Mar 9, 2026
aa0129f
chore: Remove PR-only artifacts [automated]
Mar 9, 2026
e68d1ee
Merge branch 'main' into fix/remote-conversation-hook-config
xingyaoww Mar 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@
import sys
import threading
import time
from pathlib import Path

from pydantic import SecretStr

from openhands.sdk import LLM, Conversation, RemoteConversation, Workspace, get_logger
from openhands.sdk.event import ConversationStateUpdateEvent
from openhands.sdk.hooks import HookConfig, HookDefinition, HookMatcher
from openhands.tools.preset.default import get_default_agent


logger = get_logger(__name__)

# Hook script directory - reuse the hook scripts from 33_hooks example
HOOK_SCRIPTS_DIR = (
Path(__file__).parent.parent / "01_standalone_sdk/33_hooks/hook_scripts"
)


def _stream_output(stream, prefix, target_stream):
"""Stream output from subprocess to target stream with prefix."""
Expand Down Expand Up @@ -165,10 +172,36 @@ def event_callback(event):
)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: This example has grown significantly in complexity. The original showed basic RemoteConversation usage (~50 lines). Now it's a comprehensive hook testing harness (~350 lines) that deliberately creates broken Python files to test stop hook denial and retry logic.

For a "01_" introductory example, consider splitting this into:

  • 01_convo_with_local_agent_server.py - basic usage (~50 lines)
  • 02_hooks_with_stop_validation.py - comprehensive hook testing (current content)

The comprehensive demonstration is valuable for showing hook capabilities, but might be better as a separate, clearly-labeled advanced example.

Not blocking - this is an organizational suggestion to improve discoverability for users learning the basics.

logger.info(f"Output: {result.stdout}")

# Configure hooks - demonstrating the hooks system with RemoteConversation
# Server-side hooks (PreToolUse, PostToolUse, UserPromptSubmit, Stop) are
# executed by the agent server. Client-side hooks (SessionStart, SessionEnd)
# are executed locally.
log_file = Path("/tmp/tool_usage.log")

hook_config = HookConfig(
# PostToolUse hook - logs all tool usage to a file
# Note: This won't work with RemoteConversation (warning will be shown)
# but demonstrates how hooks would be configured
post_tool_use=[
HookMatcher(
matcher="*",
hooks=[
HookDefinition(
command=(
f"LOG_FILE={log_file} {HOOK_SCRIPTS_DIR / 'log_tools.sh'}"
),
timeout=5,
)
],
)
],
)

conversation = Conversation(
agent=agent,
workspace=workspace,
callbacks=[event_callback],
hook_config=hook_config,
)
assert isinstance(conversation, RemoteConversation)

Expand Down
3 changes: 2 additions & 1 deletion openhands-sdk/openhands/sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
RemoteConversation,
)
from openhands.sdk.conversation.conversation_stats import ConversationStats
from openhands.sdk.event import Event, LLMConvertibleEvent
from openhands.sdk.event import Event, HookExecutionEvent, LLMConvertibleEvent
from openhands.sdk.event.llm_convertible import MessageEvent
from openhands.sdk.io import FileStore, LocalFileStore
from openhands.sdk.llm import (
Expand Down Expand Up @@ -92,6 +92,7 @@
"MCPToolDefinition",
"MCPToolObservation",
"MessageEvent",
"HookExecutionEvent",
"create_mcp_tools",
"get_logger",
"Conversation",
Expand Down
2 changes: 2 additions & 0 deletions openhands-sdk/openhands/sdk/agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ def init_state(
dynamic_context=TextContent(text=dynamic_context)
if dynamic_context
else None,
# Include hook_config from state for observability
hook_config=state.hook_config,
)
on_event(event)

Expand Down
6 changes: 6 additions & 0 deletions openhands-sdk/openhands/sdk/conversation/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
if TYPE_CHECKING:
from openhands.sdk.agent.base import AgentBase
from openhands.sdk.conversation.state import ConversationExecutionStatus
from openhands.sdk.hooks import HookConfig


CallbackType = TypeVar(
Expand Down Expand Up @@ -95,6 +96,11 @@ def stats(self) -> ConversationStats:
"""The conversation statistics."""
...

@property
def hook_config(self) -> "HookConfig | None":
"""The hook configuration for this conversation."""
...


class BaseConversation(ABC):
"""Abstract base class for conversation implementations.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,9 @@ def _ensure_plugins_loaded(self) -> None:

# Set up hook processor with the combined config
if final_hook_config is not None:
# Store final hook_config in state for observability
self._state.hook_config = final_hook_config

self._hook_processor, self._on_event = create_hook_callback(
hook_config=final_hook_config,
working_dir=str(self.workspace.working_dir),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
from openhands.sdk.hooks import (
HookConfig,
HookEventProcessor,
HookEventType,
HookManager,
)
from openhands.sdk.llm import LLM, Message, TextContent
Expand Down Expand Up @@ -531,6 +530,15 @@ def stats(self) -> ConversationStats:
stats_data = info.get("stats", {})
return ConversationStats.model_validate(stats_data)

@property
def hook_config(self) -> HookConfig | None:
"""Get hook configuration (fetched from remote)."""
info = self._get_conversation_info()
hook_config_data = info.get("hook_config")
if hook_config_data is not None:
return HookConfig.model_validate(hook_config_data)
return None

def model_dump(self, **_kwargs):
"""Get a dictionary representation of the remote state."""
info = self._get_conversation_info()
Expand Down Expand Up @@ -654,6 +662,8 @@ def __init__(
"tool_module_qualnames": tool_qualnames,
# Include plugins to load on server
"plugins": [p.model_dump() for p in plugins] if plugins else None,
# Include hook_config for server-side hooks
"hook_config": hook_config.model_dump() if hook_config else None,
}
if stuck_detection_thresholds is not None:
# Convert to StuckDetectionThresholds if dict, then serialize
Expand Down Expand Up @@ -769,17 +779,9 @@ def run_complete_callback(event: Event) -> None:

self._start_observability_span(str(self._id))
if hook_config is not None:
unsupported = (
HookEventType.PRE_TOOL_USE,
HookEventType.POST_TOOL_USE,
HookEventType.USER_PROMPT_SUBMIT,
HookEventType.STOP,
)
if any(hook_config.has_hooks_for_event(t) for t in unsupported):
logger.warning(
"RemoteConversation only supports SessionStart/SessionEnd hooks; "
"other hook types will not be enforced."
)
# Server-side hooks (PreToolUse, PostToolUse, UserPromptSubmit, Stop)
# are handled by the server - we send hook_config in the payload.
# Client-side hooks (SessionStart, SessionEnd) are handled locally here.
hook_manager = HookManager(
config=hook_config,
working_dir=os.getcwd(),
Expand Down
12 changes: 12 additions & 0 deletions openhands-sdk/openhands/sdk/conversation/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from openhands.sdk.event import ActionEvent, ObservationEvent, UserRejectObservation
from openhands.sdk.event.base import Event
from openhands.sdk.event.types import EventID
from openhands.sdk.hooks import HookConfig
from openhands.sdk.io import FileStore, InMemoryFileStore, LocalFileStore
from openhands.sdk.logger import get_logger
from openhands.sdk.security.analyzer import SecurityAnalyzerBase
Expand Down Expand Up @@ -164,6 +165,17 @@ class ConversationState(OpenHandsModel):
"See https://docs.openhands.dev/sdk/guides/convo-persistence#how-state-persistence-works",
)

# Hook configuration for the conversation
hook_config: HookConfig | None = Field(
default=None,
description=(
"Hook configuration for this conversation. Includes definitions for "
"PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, "
"and Stop hooks. When set, these hooks are executed at the appropriate "
"points during conversation execution."
),
)

# ===== Private attrs (NOT Fields) =====
_fs: FileStore = PrivateAttr() # filestore for persistence
_events: EventLog = PrivateAttr() # now the storage for events
Expand Down
13 changes: 13 additions & 0 deletions openhands-sdk/openhands/sdk/event/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
CondensationSummaryEvent,
)
from openhands.sdk.event.conversation_state import ConversationStateUpdateEvent
from openhands.sdk.event.hook_execution import HookExecutionEvent
from openhands.sdk.event.llm_completion_log import LLMCompletionLogEvent
from openhands.sdk.event.llm_convertible import (
ActionEvent,
Expand Down Expand Up @@ -38,7 +39,19 @@
"CondensationRequest",
"CondensationSummaryEvent",
"ConversationStateUpdateEvent",
"HookExecutionEvent",
"LLMCompletionLogEvent",
"EventID",
"ToolCallID",
]


# Rebuild SystemPromptEvent model to resolve forward reference to HookConfig
# This must be done after all imports are complete to avoid circular import
def _rebuild_models() -> None:
from openhands.sdk.hooks import HookConfig

SystemPromptEvent.model_rebuild(_types_namespace={"HookConfig": HookConfig})


_rebuild_models()
129 changes: 129 additions & 0 deletions openhands-sdk/openhands/sdk/event/hook_execution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""Hook execution event for observability into hook execution."""

from typing import Any, Literal

from pydantic import Field
from rich.text import Text

from openhands.sdk.event.base import Event
from openhands.sdk.event.types import SourceType


HookEventType = Literal[
"PreToolUse",
"PostToolUse",
"UserPromptSubmit",
"SessionStart",
"SessionEnd",
"Stop",
]


class HookExecutionEvent(Event):
"""Event emitted when a hook is executed.

This event provides observability into hook execution, including:
- Which hook type was triggered
- The command that was run
- The result (success/blocked/error)
- Any output from the hook

This allows clients to track hook execution via the event stream.
"""

source: SourceType = Field(
default="hook", description="Source is always 'hook' for hook execution events"
)

# Hook identification
hook_event_type: HookEventType = Field(
..., description="The type of hook event that triggered this execution"
)
hook_command: str = Field(..., description="The hook command that was executed")
tool_name: str | None = Field(
default=None,
description="Tool name for PreToolUse/PostToolUse hooks",
)

# Execution result
success: bool = Field(..., description="Whether the hook executed successfully")
blocked: bool = Field(
default=False,
description="Whether the hook blocked the operation (exit code 2 or deny)",
)
exit_code: int = Field(..., description="Exit code from the hook command")

# Output
stdout: str = Field(default="", description="Standard output from the hook")
stderr: str = Field(default="", description="Standard error from the hook")
reason: str | None = Field(
default=None, description="Reason provided by hook (for blocking)"
)
additional_context: str | None = Field(
default=None,
description="Additional context injected by hook (e.g., for UserPromptSubmit)",
)
error: str | None = Field(
default=None, description="Error message if hook execution failed"
)

# Context
action_id: str | None = Field(
default=None,
description="ID of the action this hook is associated with (PreToolUse/PostToolUse)", # noqa: E501
)
message_id: str | None = Field(
default=None,
description="ID of the message this hook is associated with (UserPromptSubmit)",
)
hook_input: dict[str, Any] | None = Field(
default=None,
description="The input data that was passed to the hook",
)

@property
def visualize(self) -> Text:
"""Return Rich Text representation of this hook execution event."""
content = Text()
content.append("Hook: ", style="bold")
content.append(f"{self.hook_event_type}")
if self.tool_name:
content.append(f" ({self.tool_name})")
content.append("\n")

# Status
if self.blocked:
content.append("Status: ", style="bold")
content.append("BLOCKED", style="bold red")
if self.reason:
content.append(f" - {self.reason}")
elif self.success:
content.append("Status: ", style="bold")
content.append("SUCCESS", style="bold green")
else:
content.append("Status: ", style="bold")
content.append("FAILED", style="bold red")
if self.error:
content.append(f" - {self.error}")

content.append(f"\nExit Code: {self.exit_code}")

# Output (truncated)
if self.stdout:
output_preview = self.stdout[:200]
if len(self.stdout) > 200:
output_preview += "..."
content.append(f"\nOutput: {output_preview}")

if self.additional_context:
content.append(f"\nInjected Context: {self.additional_context[:100]}...")

return content

def __str__(self) -> str:
"""Plain text string representation for HookExecutionEvent."""
status = (
"BLOCKED" if self.blocked else ("SUCCESS" if self.success else "FAILED")
)
tool_info = f" ({self.tool_name})" if self.tool_name else ""
return f"HookExecutionEvent: {self.hook_event_type}{tool_info} - {status}"
Loading
Loading