Skip to content

Commit ea32b6d

Browse files
Python: compose Copilot session hooks correctly (#9649)
Co-authored-by: Copilot App <[email protected]>
1 parent 678c661 commit ea32b6d

3 files changed

Lines changed: 45 additions & 23 deletions

File tree

‎python/packages/github_copilot/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ When you register a `FunctionTool` declared with `approval_mode="always_require"
2020
do **not** supply your own `on_pre_tool_use` hook, `GitHubCopilotAgent` installs a default
2121
`on_pre_tool_use` hook that returns `"ask"` for that tool and defers (`None`) for all other
2222
tools. The `"ask"` decision routes to your `on_permission_request` handler, where you
23-
approve or deny the call:
23+
approve or deny the call. Other session hooks, such as `on_post_tool_use` or
24+
`on_session_start`, are preserved alongside this default approval hook:
2425

2526
```python
2627
from agent_framework import tool

‎python/packages/github_copilot/agent_framework_github_copilot/_agent.py‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1505,17 +1505,16 @@ def _build_session_hooks(
15051505
``approval_mode="always_require"`` is delegated to the Copilot SDK's native
15061506
``on_pre_tool_use`` hook:
15071507
1508-
- If the caller supplies their own session hooks -- either the SDK-native
1509-
``hooks`` dict or the convenience ``on_pre_tool_use`` handler (via per-run
1510-
``options`` or ``default_options``) -- those take precedence and are used
1511-
as-is. When both are given, the explicit ``hooks`` dict wins for any key it
1512-
defines and the ``on_pre_tool_use`` shortcut fills in that key otherwise. A
1513-
warning is logged naming any approval-required tool that will therefore not
1514-
be automatically gated, since the caller's hooks are responsible for
1515-
enforcing approval.
1508+
- If the caller supplies their own ``on_pre_tool_use`` handler -- either in
1509+
the SDK-native ``hooks`` dict or through the convenience option (via per-run
1510+
``options`` or ``default_options``) -- it takes precedence. When both are
1511+
given, the explicit ``hooks`` dict wins for any key it defines and the
1512+
shortcut fills in that key otherwise. A warning names any approval-required
1513+
tool that the caller's pre-tool-use handler is responsible for gating.
15161514
- Otherwise, when any approval-required tool is present, a default hook is
15171515
installed that returns ``"ask"`` for those tools (routing the decision to
15181516
``on_permission_request``) and defers (``None``) for all other tools.
1517+
Unrelated caller hooks are preserved and do not replace this default.
15191518
- The default hook is **not** installed when the deprecated
15201519
``on_function_approval`` callback is configured: in that case approval is
15211520
enforced inside the tool handler (see :meth:`_tool_to_copilot_tool`) to
@@ -1532,12 +1531,12 @@ def _build_session_hooks(
15321531
The hooks to register for the session, or ``None`` if none are needed.
15331532
"""
15341533
user_hook: PreToolUseHandler | None = options.get("on_pre_tool_use") or self._on_pre_tool_use
1535-
caller_hooks: Mapping[str, Any] | None = options.get("hooks")
1534+
caller_hooks: SessionHooks | None = options.get("hooks")
15361535

15371536
# Combine caller-provided hooks: the SDK-native ``hooks`` dict plus the
15381537
# convenience ``on_pre_tool_use`` shortcut. The explicit dict wins for the
15391538
# keys it defines; the shortcut only fills in ``on_pre_tool_use`` otherwise.
1540-
combined: dict[str, Any] = {}
1539+
combined: SessionHooks = {}
15411540
if user_hook is not None:
15421541
combined["on_pre_tool_use"] = user_hook
15431542
if caller_hooks:
@@ -1547,7 +1546,7 @@ def _build_session_hooks(
15471546
tool.name for tool in all_tools if isinstance(tool, FunctionTool) and tool.approval_mode == "always_require"
15481547
}
15491548

1550-
if combined:
1549+
if combined.get("on_pre_tool_use") is not None:
15511550
if approval_required_names:
15521551
logger.warning(
15531552
"Custom session hooks are configured, so %d approval-required tool(s) (%s) "
@@ -1556,15 +1555,15 @@ def _build_session_hooks(
15561555
len(approval_required_names),
15571556
", ".join(sorted(approval_required_names)),
15581557
)
1559-
return cast("SessionHooks", combined)
1558+
return combined
15601559

15611560
if not approval_required_names:
1562-
return None
1561+
return combined or None
15631562

15641563
# The deprecated on_function_approval callback enforces approval in the tool
15651564
# handler; don't also install the default ask-hook (which would double-gate).
15661565
if self._function_approval_handler is not None:
1567-
return None
1566+
return combined or None
15681567

15691568
def default_pre_tool_use(
15701569
hook_input: Mapping[str, Any],
@@ -1580,7 +1579,8 @@ def default_pre_tool_use(
15801579
}
15811580
return None
15821581

1583-
return {"on_pre_tool_use": default_pre_tool_use}
1582+
combined["on_pre_tool_use"] = default_pre_tool_use
1583+
return combined
15841584

15851585
def _session_run_lock(self, service_session_id: str) -> asyncio.Lock:
15861586
"""Return the lock that serializes runs on one Copilot service session."""

‎python/packages/github_copilot/tests/test_github_copilot_agent.py‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2959,26 +2959,47 @@ def dangerous(path: str) -> str:
29592959
hooks = agent._build_session_hooks([dangerous], {"on_pre_tool_use": runtime_hook}) # type: ignore[reportPrivateUsage]
29602960
assert hooks == {"on_pre_tool_use": runtime_hook}
29612961

2962-
async def test_default_hook_forwarded_to_create_session(
2962+
@pytest.mark.parametrize("streaming", [False, True])
2963+
async def test_default_hook_forwarded_with_unrelated_hooks(
29632964
self,
29642965
mock_client: MagicMock,
29652966
mock_session: MagicMock,
29662967
assistant_message_event: SessionEvent,
2968+
assistant_delta_event: SessionEvent,
2969+
session_idle_event: SessionEvent,
2970+
streaming: bool,
29672971
) -> None:
2968-
"""An always_require tool causes the default hook to be forwarded to the SDK session."""
2972+
"""Unrelated hooks are forwarded without suppressing approval in either run path."""
29692973
mock_session.send_and_wait.return_value = assistant_message_event
2974+
post_tool_use = MagicMock()
29702975

29712976
@tool(approval_mode="always_require")
29722977
def dangerous(path: str) -> str:
29732978
"""A tool that requires human approval."""
29742979
return f"deleted {path}"
29752980

2976-
agent = GitHubCopilotAgent(client=mock_client, tools=[dangerous])
2977-
await agent.run("hello")
2981+
agent = GitHubCopilotAgent(
2982+
client=mock_client,
2983+
tools=[dangerous],
2984+
default_options=cast(Any, {"hooks": {"on_post_tool_use": post_tool_use}}),
2985+
)
2986+
if streaming:
2987+
events = [assistant_delta_event, session_idle_event]
2988+
2989+
def mock_on(handler: Any) -> Any:
2990+
for event in events:
2991+
handler(event)
2992+
return lambda: None
29782993

2979-
hooks = mock_client.create_session.call_args.kwargs["hooks"]
2980-
assert hooks is not None
2981-
assert "on_pre_tool_use" in hooks
2994+
mock_session.on = mock_on
2995+
await agent.run("hello", stream=True).get_final_response()
2996+
else:
2997+
await agent.run("hello")
2998+
2999+
session_hooks = mock_client.create_session.call_args.kwargs["hooks"]
3000+
assert session_hooks["on_post_tool_use"] is post_tool_use
3001+
decision = session_hooks["on_pre_tool_use"](pre_tool_use_input("dangerous"), {"session_id": "s"})
3002+
assert decision["permissionDecision"] == "ask"
29823003

29833004

29843005
class TestGitHubCopilotAgentDeprecatedFunctionApproval:

0 commit comments

Comments
 (0)