Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/openrouter_agent/hooks_emit.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ async def execute_handler_chain(
tool_name: Optional[str] = None,
result_schema: Optional[Type[BaseModel]] = None,
on_async_timeout: Optional[Callable[[str], None]] = None,
normalize_payload: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
) -> EmitResult:
options = _ChainOptions(
hook_name=hook_name,
Expand Down Expand Up @@ -100,7 +101,7 @@ async def execute_handler_chain(
if behavior and behavior.mutations:
applied = _apply_mutations(current_payload, result, behavior.mutations)
if applied is not current_payload:
current_payload = applied
current_payload = normalize_payload(applied) if normalize_payload is not None else applied
mutated = True

if behavior and behavior.block_field and _is_block_triggered(result, behavior.block_field):
Expand Down
2 changes: 2 additions & 0 deletions src/openrouter_agent/hooks_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ async def emit(
*,
tool_name: Optional[str] = None,
session_id: Optional[str] = None,
normalize_payload: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
) -> EmitResult:
"""Validate the payload (and each handler's result) against the
registered schemas, invoke matching handlers, and return results.
Expand Down Expand Up @@ -134,6 +135,7 @@ async def emit(
tool_name=tool_name,
result_schema=result_schema,
on_async_timeout=lambda _name: cancel_event.set(),
normalize_payload=normalize_payload,
)

has_detached_work = len(result.pending) > 0
Expand Down
167 changes: 129 additions & 38 deletions src/openrouter_agent/model_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,18 @@
import warnings
from typing import Any, AsyncIterator, Dict, List, Mapping, Optional, Sequence, Tuple

from ._utils import dump, get_field, is_async_iterable, json_dumps, maybe_await, sdk_request_kwargs
from pydantic import BaseModel

from ._utils import (
dump,
get_field,
is_async_iterable,
json_dumps,
maybe_await,
sdk_request_kwargs,
set_field,
validate_schema,
)
from .async_params import resolve_async_functions
from .conversation_state import (
append_to_messages,
Expand Down Expand Up @@ -93,17 +104,73 @@ def _extract_model_call_usage(usage: Any) -> Optional[Dict[str, Any]]:
return result


def _is_user_string_message(value: Any) -> bool:
return isinstance(value, Mapping) and value.get("role") == "user" and isinstance(value.get("content"), str)
def _tool_input_for_hooks(tool: Tool, arguments: Any) -> Dict[str, Any]:
parsed = parsed_tool_input(tool, arguments)
if isinstance(parsed, Mapping):
return dict(parsed)
return dict(arguments) if isinstance(arguments, Mapping) else {}


def _revalidate_mutated_arguments(tool: Tool, mutated: Any) -> Any:
if isinstance(mutated, str):
return mutated
try:
validated = validate_schema(get_tool_function(tool).get("input_schema"), mutated)
except Exception:
return mutated
if isinstance(validated, BaseModel):
return validated.model_dump(by_alias=True)
return validated


def _is_text_content_part(part: Any) -> bool:
return get_field(part, "type") in {"input_text", "text"} and isinstance(get_field(part, "text"), str)


def _extract_user_message_prompt(value: Any) -> Optional[str]:
if get_field(value, "role") != "user":
return None
content = get_field(value, "content")
if isinstance(content, str):
return content
if isinstance(content, list):
texts = [get_field(part, "text") for part in content if _is_text_content_part(part)]
if texts:
return "\n".join(texts)
return None


def _find_latest_user_string_index(items: Sequence[Any]) -> int:
def _find_latest_user_prompt_index(items: Sequence[Any]) -> int:
for index in range(len(items) - 1, -1, -1):
if _is_user_string_message(items[index]):
if _extract_user_message_prompt(items[index]) is not None:
return index
return -1


def _update_field(item: Any, name: str, value: Any) -> Any:
if isinstance(item, Mapping):
return {**item, name: value}
return set_field(item, name, value)


def _replace_user_message_prompt(item: Any, mutated_prompt: str) -> Any:
content = get_field(item, "content")
if isinstance(content, str):
return _update_field(item, "content", mutated_prompt)
if isinstance(content, list):
new_parts: List[Any] = []
replaced = False
for part in content:
if _is_text_content_part(part):
if not replaced:
new_parts.append(_update_field(part, "text", mutated_prompt))
replaced = True
else:
new_parts.append(part)
return _update_field(item, "content", new_parts)
return item


def _is_specific_forced_tool_choice(tool_choice: Any) -> bool:
"""Return True when `tool_choice` pins a specific tool (e.g. a named function).

Expand Down Expand Up @@ -416,11 +483,16 @@ async def _emit_permission_request(self, call: ParsedToolCall, tools: Sequence[T
else:
risk_level = "low"

tool_input = (
_tool_input_for_hooks(tool, call.arguments)
if tool is not None
else (call.arguments if isinstance(call.arguments, dict) else {})
)
emitted = await self._hooks.emit(
"PermissionRequest",
{
"tool_name": call.name,
"tool_input": call.arguments if isinstance(call.arguments, dict) else {},
"tool_input": tool_input,
"risk_level": risk_level,
},
tool_name=call.name,
Expand All @@ -446,21 +518,34 @@ async def _maybe_run_user_prompt_submit(self, input_value: Any) -> Any:
return input_value

if isinstance(input_value, list):
target_index = _find_latest_user_string_index(input_value)
target_index = _find_latest_user_prompt_index(input_value)
if target_index == -1:
return input_value
prompt = input_value[target_index]["content"]
emitted = await self._hooks.emit("UserPromptSubmit", {"prompt": prompt}, session_id=self._session_id)
extracted = _extract_user_message_prompt(input_value[target_index])
if extracted is None:
return input_value
emitted = await self._hooks.emit("UserPromptSubmit", {"prompt": extracted}, session_id=self._session_id)
if emitted.blocked:
reject = next((r.get("reject") for r in emitted.results if r.get("reject")), None)
raise ValueError(reject if isinstance(reject, str) else "Prompt rejected by hook")
if not emitted.mutated:
return input_value
mutated_prompt = emitted.final_payload.get("prompt", prompt)
mutated_prompt = emitted.final_payload.get("prompt", extracted)
new_items = list(input_value)
new_items[target_index] = {**new_items[target_index], "content": mutated_prompt}
new_items[target_index] = _replace_user_message_prompt(new_items[target_index], mutated_prompt)
return new_items

single_prompt = _extract_user_message_prompt(input_value)
if single_prompt is not None:
emitted = await self._hooks.emit("UserPromptSubmit", {"prompt": single_prompt}, session_id=self._session_id)
if emitted.blocked:
reject = next((r.get("reject") for r in emitted.results if r.get("reject")), None)
raise ValueError(reject if isinstance(reject, str) else "Prompt rejected by hook")
if not emitted.mutated:
return input_value
mutated_prompt = emitted.final_payload.get("prompt", single_prompt)
return _replace_user_message_prompt(input_value, mutated_prompt)

return input_value

async def _inject_append_prompt_message(self, prompt: str, current_request: Dict[str, Any]) -> None:
Expand Down Expand Up @@ -508,6 +593,31 @@ async def _run_stop_hook(self, force_resume_count: int, current_request: Dict[st
def _find_tool(self, name: str, tools: Sequence[Tool]) -> Optional[Tool]:
return next((t for t in tools if is_client_tool(t) and get_tool_function(t).get("name") == name), None)

async def _emit_pre_tool_use(self, tool: Tool, call: ParsedToolCall) -> Tuple[Optional[str], ParsedToolCall]:
"""Emit PreToolUse with schema-parsed arguments and re-validate any mutation."""
assert self._hooks is not None
original_input = _tool_input_for_hooks(tool, call.arguments)
pre = await self._hooks.emit(
"PreToolUse",
{"tool_name": call.name, "tool_input": original_input},
tool_name=call.name,
session_id=self._session_id,
normalize_payload=lambda payload: {
**payload,
"tool_input": _tool_input_for_hooks(tool, payload.get("tool_input")),
},
)
if pre.blocked:
block = next((r.get("block") for r in pre.results if r.get("block")), None)
reason = block if isinstance(block, str) else "Blocked by PreToolUse hook"
return reason, call
if pre.mutated:
mutated_inputs = [r["mutated_input"] for r in pre.results if r.get("mutated_input") is not None]
raw_mutated = mutated_inputs[-1] if mutated_inputs else pre.final_payload.get("tool_input")
revalidated = _revalidate_mutated_arguments(tool, raw_mutated)
return None, dataclasses.replace(call, arguments=revalidated)
return None, call

async def _run_tool_with_hooks(
self, tool: Tool, call: ParsedToolCall, context: Mapping[str, Any]
) -> Dict[str, Any]:
Expand All @@ -533,19 +643,9 @@ async def _run_tool_with_hooks(

effective_call = call
if self._hooks and call.pre_tool_use_applied is not True:
original_input = call.arguments if isinstance(call.arguments, dict) else {}
pre = await self._hooks.emit(
"PreToolUse",
{"tool_name": call.name, "tool_input": original_input},
tool_name=call.name,
session_id=self._session_id,
)
if pre.blocked:
block = next((r.get("block") for r in pre.results if r.get("block")), None)
reason = block if isinstance(block, str) else "Blocked by PreToolUse hook"
return {"type": "hook_blocked", "call": call, "reason": reason}
if pre.mutated:
effective_call = dataclasses.replace(call, arguments=pre.final_payload.get("tool_input"))
blocked_reason, effective_call = await self._emit_pre_tool_use(tool, call)
if blocked_reason is not None:
return {"type": "hook_blocked", "call": call, "reason": blocked_reason}

started = time.monotonic()
result = await execute_tool(
Expand All @@ -559,7 +659,7 @@ async def _run_tool_with_hooks(
duration_ms = (time.monotonic() - started) * 1000

if self._hooks and result is not None:
tool_input = effective_call.arguments if isinstance(effective_call.arguments, dict) else {}
tool_input = _tool_input_for_hooks(tool, effective_call.arguments)
if result.get("error") is not None:
await self._hooks.emit(
"PostToolUseFailure",
Expand Down Expand Up @@ -602,21 +702,12 @@ async def _prepare_tool_calls_for_approval(
prepared.append(call)
continue

original_input = call.arguments if isinstance(call.arguments, dict) else {}
pre = await self._hooks.emit(
"PreToolUse",
{"tool_name": call.name, "tool_input": original_input},
tool_name=call.name,
session_id=self._session_id,
)
if pre.blocked:
block = next((result.get("block") for result in pre.results if result.get("block")), None)
reason = block if isinstance(block, str) else "Blocked by PreToolUse hook"
blocked.append(create_rejected_result(call.id, call.name, reason))
blocked_reason, effective_call = await self._emit_pre_tool_use(tool, call)
if blocked_reason is not None:
blocked.append(create_rejected_result(call.id, call.name, blocked_reason))
continue

arguments = pre.final_payload.get("tool_input") if pre.mutated else call.arguments
prepared.append(dataclasses.replace(call, arguments=arguments, pre_tool_use_applied=True))
prepared.append(dataclasses.replace(effective_call, pre_tool_use_applied=True))

return prepared, blocked

Expand Down
Loading
Loading