Skip to content
Open
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
100 changes: 99 additions & 1 deletion src/claude_agent_sdk/_internal/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import uuid
from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Mapping
from contextlib import suppress
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal

import anyio
Expand All @@ -30,6 +31,11 @@
)
from ._task_compat import TaskHandle, spawn_detached
from .sdk_mcp_bridge import SdkMcpBridge
from .sessions import (
_parent_ids_from_agent_metadata,
_read_agent_metadata_sidecar,
_resolve_subagents_dir,
)
from .transport import Transport

if TYPE_CHECKING:
Expand Down Expand Up @@ -265,6 +271,9 @@ def __init__(
self._initialized = False
self._closed = False
self._initialization_result: dict[str, Any] | None = None
self._session_id: str | None = None
self._session_cwd: str | None = None
self._parent_tool_use_ids: dict[str, str] = {}

# Set when the run is over, so the stdin-closing waiter can wake; see
# _read_messages and _inflight_tasks below (#1088, #1190). Work the CLI
Expand Down Expand Up @@ -491,6 +500,12 @@ async def _read_messages(self) -> None:
# Track task lifecycle frames so results can tell "one turn
# ended" apart from "the run is done" (see #1088).
if msg_type == "system":
if (
message.get("subtype") == "init"
and message.get("parent_tool_use_id") is None
):
self._session_id = message.get("session_id")
self._session_cwd = message.get("cwd")
had_tasks_in_flight = bool(self._inflight_tasks)
self._track_task_lifecycle(message)
if had_tasks_in_flight and not self._inflight_tasks:
Expand Down Expand Up @@ -628,6 +643,72 @@ async def _read_messages(self) -> None:
self._message_send.send_nowait({"type": "end"})
self._message_send.close()

def _parent_tool_use_id_for_agent(
self,
agent_id: str | None,
wire_id: Any,
transcript_path: str | None = None,
session_id: str | None = None,
cwd: str | None = None,
) -> str | None:
"""Resolve a sub-agent's spawning tool call from the wire or CLI sidecar.

Current CLI versions do not include this ID on control requests. The
sidecar is the same source used by get_subagent_messages(); a missing
or unreadable one leaves the value unknown rather than delaying hooks.
"""
if not agent_id:
return None
if isinstance(wire_id, str) and wire_id:
self._parent_tool_use_ids[agent_id] = wire_id
return wire_id
if agent_id in self._parent_tool_use_ids:
return self._parent_tool_use_ids[agent_id]
if "/" in agent_id or "\\" in agent_id:
return None

paths: list[Path] = []
if transcript_path:
transcript = Path(transcript_path)
if transcript.name == f"agent-{agent_id}.jsonl":
paths.append(transcript)
resolved_session_id = session_id or self._session_id
base: Path | None = None
if resolved_session_id:
with suppress(OSError):
base = _resolve_subagents_dir(
resolved_session_id, cwd or self._session_cwd or str(Path.cwd())
)
if base is not None:
paths.append(base / f"agent-{agent_id}.jsonl")
for path in paths:
try:
parent_id, _ = _parent_ids_from_agent_metadata(
_read_agent_metadata_sidecar(path)
)
except OSError:
continue
if parent_id:
self._parent_tool_use_ids[agent_id] = parent_id
return parent_id
if base is not None:
# Nested workflows keep their sidecars below subagents/. Scan
# only if the direct path did not provide an ID.
with suppress(OSError):
for meta in base.rglob("agent-*.meta.json"):
if meta.name != f"agent-{agent_id}.meta.json":
continue
transcript = meta.with_name(
meta.name[: -len(".meta.json")] + ".jsonl"
)
parent_id, _ = _parent_ids_from_agent_metadata(
_read_agent_metadata_sidecar(transcript)
)
if parent_id:
self._parent_tool_use_ids[agent_id] = parent_id
return parent_id
return None

async def _handle_control_request(self, request: SDKControlRequest) -> None:
"""Handle incoming control request from CLI."""
request_id = request["request_id"]
Expand All @@ -654,6 +735,11 @@ async def _handle_control_request(self, request: SDKControlRequest) -> None:
],
tool_use_id=permission_request.get("tool_use_id"),
agent_id=permission_request.get("agent_id"),
parent_tool_use_id=await anyio.to_thread.run_sync(
self._parent_tool_use_id_for_agent,
permission_request.get("agent_id"),
permission_request.get("parent_tool_use_id"),
),
blocked_path=permission_request.get("blocked_path"),
decision_reason=permission_request.get("decision_reason"),
title=permission_request.get("title"),
Expand Down Expand Up @@ -700,8 +786,20 @@ async def _handle_control_request(self, request: SDKControlRequest) -> None:
if not callback:
raise Exception(f"No hook callback found for ID: {callback_id}")

hook_input = request_data.get("input")
if isinstance(hook_input, dict) and hook_input.get("agent_id"):
parent_id = await anyio.to_thread.run_sync(
self._parent_tool_use_id_for_agent,
hook_input.get("agent_id"),
hook_input.get("parent_tool_use_id"),
hook_input.get("transcript_path"),
hook_input.get("session_id"),
hook_input.get("cwd"),
)
if parent_id and not hook_input.get("parent_tool_use_id"):
hook_input = {**hook_input, "parent_tool_use_id": parent_id}
hook_output = await callback(
request_data.get("input"),
hook_input,
request_data.get("tool_use_id"),
{"signal": None}, # TODO: Add abort signal support
)
Expand Down
11 changes: 11 additions & 0 deletions src/claude_agent_sdk/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,9 @@ class ToolPermissionContext:
button labels or compact UI."""
description: str | None = None
"""Human-readable subtitle for the permission UI."""
parent_tool_use_id: str | None = None
"""The parent Agent tool call that spawned this sub-agent, when available.
Kept last so positional construction of older fields remains compatible."""


# Match TypeScript's PermissionResult structure
Expand Down Expand Up @@ -379,10 +382,15 @@ class _SubagentContextMixin(TypedDict, total=False):
agent_type: Agent type name (e.g. "general-purpose", "code-reviewer").
Present inside a sub-agent (alongside agent_id), or on the main thread
of a session started with --agent (without agent_id).

parent_tool_use_id: The Agent tool call in the parent session that spawned
this sub-agent. Absent on the main thread or when neither the CLI nor its
local sub-agent metadata provides the ID.
"""

agent_id: str
agent_type: str
parent_tool_use_id: str


class PreToolUseHookInput(BaseHookInput, _SubagentContextMixin):
Expand Down Expand Up @@ -488,6 +496,7 @@ class SubagentStopHookInput(BaseHookInput):
hook_event_name: Literal["SubagentStop"]
stop_hook_active: bool
agent_id: str
parent_tool_use_id: NotRequired[str]
agent_transcript_path: str
agent_type: str
last_assistant_message: NotRequired[str]
Expand Down Expand Up @@ -520,6 +529,7 @@ class SubagentStartHookInput(BaseHookInput):

hook_event_name: Literal["SubagentStart"]
agent_id: str
parent_tool_use_id: NotRequired[str]
agent_type: str


Expand Down Expand Up @@ -2933,6 +2943,7 @@ class SDKControlPermissionRequest(TypedDict):
description: NotRequired[str]
tool_use_id: str
agent_id: NotRequired[str]
parent_tool_use_id: NotRequired[str]


class SDKControlInitializeRequest(TypedDict):
Expand Down
135 changes: 135 additions & 0 deletions tests/test_tool_callbacks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tests for tool permission callbacks and hook callbacks."""

import json
from pathlib import Path
from typing import Any

import pytest
Expand Down Expand Up @@ -415,6 +416,86 @@ async def capture_callback(
assert received_context is not None
assert received_context.tool_use_id == "toolu_01XYZ789"
assert received_context.agent_id is None
assert received_context.parent_tool_use_id is None

@pytest.mark.anyio
async def test_permission_callback_receives_parent_tool_use_id(self):
received_context = None

async def capture_callback(
tool_name: str, input_data: dict, context: ToolPermissionContext
) -> PermissionResultAllow:
nonlocal received_context
received_context = context
return PermissionResultAllow()

query = Query(
transport=MockTransport(),
is_streaming_mode=True,
can_use_tool=capture_callback,
)
await query._handle_control_request(
{
"type": "control_request",
"request_id": "parent-permission",
"request": {
"subtype": "can_use_tool",
"tool_name": "Bash",
"input": {},
"tool_use_id": "toolu_child",
"agent_id": "agent-1",
"parent_tool_use_id": "toolu_spawn",
},
}
)
assert received_context.parent_tool_use_id == "toolu_spawn"

@pytest.mark.anyio
@pytest.mark.parametrize("nested", [False, True])
async def test_permission_callback_uses_subagent_sidecar(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, nested: bool
):
subagents = tmp_path / "subagents"
subagents.mkdir()
sidecar_dir = subagents / "workflows" / "run-1" if nested else subagents
sidecar_dir.mkdir(parents=True, exist_ok=True)
(sidecar_dir / "agent-agent-1.meta.json").write_text(
json.dumps({"toolUseId": "toolu_spawn"})
)
monkeypatch.setattr(
"claude_agent_sdk._internal.query._resolve_subagents_dir",
lambda session_id, cwd: subagents,
)
received_context = None

async def capture_callback(
tool_name: str, input_data: dict, context: ToolPermissionContext
) -> PermissionResultAllow:
nonlocal received_context
received_context = context
return PermissionResultAllow()

query = Query(
transport=MockTransport(),
is_streaming_mode=True,
can_use_tool=capture_callback,
)
query._session_id = "550e8400-e29b-41d4-a716-446655440000"
query._session_cwd = str(tmp_path)
await query._handle_control_request(
{
"type": "control_request",
"request_id": "parent-sidecar-permission",
"request": {
"subtype": "can_use_tool",
"tool_name": "Bash",
"input": {},
"tool_use_id": "toolu_child",
"agent_id": "agent-1",
},
}
)
assert received_context.parent_tool_use_id == "toolu_spawn"

@pytest.mark.anyio
async def test_permission_callback_receives_decision_reason(self):
Expand Down Expand Up @@ -977,6 +1058,60 @@ async def subagent_start_hook(
assert result["hookSpecificOutput"]["hookEventName"] == "SubagentStart"
assert result["hookSpecificOutput"]["additionalContext"] == "Subagent approved"

@pytest.mark.anyio
@pytest.mark.parametrize(
"hook_event_name",
[
"PreToolUse",
"PostToolUse",
"PostToolUseFailure",
"PermissionRequest",
"SubagentStart",
"SubagentStop",
],
)
async def test_subagent_hook_receives_parent_from_sidecar(
self, tmp_path: Path, hook_event_name: str
):
transcript = tmp_path / "agent-worker.jsonl"
transcript.write_text("")
(tmp_path / "agent-worker.meta.json").write_text(
json.dumps({"toolUseId": "toolu_spawn"})
)
received_input = None

async def capture_hook(
input_data: HookInput, tool_use_id: str | None, context: HookContext
) -> HookJSONOutput:
nonlocal received_input
received_input = input_data
return {}

query = Query(transport=MockTransport(), is_streaming_mode=True)
query.hook_callbacks["parent-hook"] = capture_hook
await query._handle_control_request(
{
"type": "control_request",
"request_id": "parent-hook-request",
"request": {
"subtype": "hook_callback",
"callback_id": "parent-hook",
"input": {
"hook_event_name": hook_event_name,
"agent_id": "worker",
"session_id": "550e8400-e29b-41d4-a716-446655440000",
"transcript_path": str(transcript),
"cwd": str(tmp_path),
"tool_name": "Bash",
"tool_input": {},
"tool_use_id": "toolu_child",
},
"tool_use_id": "toolu_child",
},
}
)
assert received_input["parent_tool_use_id"] == "toolu_spawn"

@pytest.mark.anyio
async def test_post_tool_use_hook_with_updated_mcp_output(self):
"""Test PostToolUse hook returning updatedMCPToolOutput."""
Expand Down