clawd-code-sdk 1.0.27__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/PKG-INFO +1 -1
  2. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/pyproject.toml +1 -1
  3. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_internal/query.py +37 -284
  4. clawd_code_sdk-1.1.0/src/clawd_code_sdk/anthropic_stream.py +205 -0
  5. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/client.py +143 -47
  6. clawd_code_sdk-1.1.0/src/clawd_code_sdk/instrumentation.py +198 -0
  7. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/__init__.py +24 -2
  8. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/context_usage.py +1 -0
  9. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/control.py +58 -11
  10. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/hooks.py +2 -0
  11. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/options.py +3 -0
  12. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/output_types.py +22 -1
  13. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/permissions.py +27 -1
  14. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/server_info.py +4 -1
  15. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/settings.py +13 -1
  16. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/mock_claude_server.py +11 -0
  17. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_session.py +25 -9
  18. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_streaming_client.py +14 -5
  19. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_tool_callbacks.py +4 -1
  20. clawd_code_sdk-1.0.27/src/clawd_code_sdk/instrumentation.py +0 -315
  21. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/.gitignore +0 -0
  22. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/LICENSE +0 -0
  23. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/README.md +0 -0
  24. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/__init__.py +0 -0
  25. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_bundled/.gitignore +0 -0
  26. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_errors.py +0 -0
  27. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_internal/__init__.py +0 -0
  28. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_internal/transport/__init__.py +0 -0
  29. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_internal/transport/subprocess_cli.py +0 -0
  30. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_internal/transport/subprocess_utils.py +0 -0
  31. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/_version.py +0 -0
  32. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/list_sessions.py +0 -0
  33. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/mcp_utils.py +0 -0
  34. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/agents.py +0 -0
  35. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/anthropic_types.py +0 -0
  36. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/base.py +0 -0
  37. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/content_blocks.py +0 -0
  38. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/input_types.py +0 -0
  39. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/mcp.py +0 -0
  40. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/messages.py +0 -0
  41. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/prompt_requests.py +0 -0
  42. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/prompts.py +0 -0
  43. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/session.py +0 -0
  44. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/system_messages.py +0 -0
  45. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/thinking.py +0 -0
  46. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/models/usage.py +0 -0
  47. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/py.typed +0 -0
  48. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/session.py +0 -0
  49. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/storage/ARCHITECTURE.md +0 -0
  50. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/storage/__init__.py +0 -0
  51. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/storage/helpers.py +0 -0
  52. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/storage/models.py +0 -0
  53. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/storage/replay.py +0 -0
  54. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/src/clawd_code_sdk/usage.py +0 -0
  55. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/__init__.py +0 -0
  56. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/conftest.py +0 -0
  57. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/__init__.py +0 -0
  58. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_agents_and_settings.py +0 -0
  59. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_dynamic_control.py +0 -0
  60. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_hook_events.py +0 -0
  61. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_hooks.py +0 -0
  62. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_include_partial_messages.py +0 -0
  63. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_mcp_resources.py +0 -0
  64. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_mcp_tools.py +0 -0
  65. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_sdk_mcp_resources.py +0 -0
  66. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_sdk_mcp_tools.py +0 -0
  67. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_slash_commands.py +0 -0
  68. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_stderr_callback.py +0 -0
  69. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_storage_parsing.py +0 -0
  70. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_structured_output.py +0 -0
  71. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_subagent_invocation.py +0 -0
  72. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/e2e/test_tool_permissions.py +0 -0
  73. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/mcp_server.py +0 -0
  74. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_changelog.py +0 -0
  75. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_client.py +0 -0
  76. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_errors.py +0 -0
  77. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_image.png +0 -0
  78. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_integration.py +0 -0
  79. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_message_parser.py +0 -0
  80. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_sdk_mcp_integration.py +0 -0
  81. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_subprocess_buffering.py +0 -0
  82. {clawd_code_sdk-1.0.27 → clawd_code_sdk-1.1.0}/tests/test_transport.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clawd-code-sdk
3
- Version: 1.0.27
3
+ Version: 1.1.0
4
4
  Summary: Python SDK for Claude Code
5
5
  Project-URL: Documentation, https://github.com/phil65/claude-agent-sdk-python
6
6
  Project-URL: Homepage, https://github.com/phil65/claude-agent-sdk-python
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "clawd-code-sdk"
3
- version = "1.0.27"
3
+ version = "1.1.0"
4
4
  description = "Python SDK for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -8,7 +8,7 @@ from dataclasses import replace
8
8
  import logging
9
9
  import math
10
10
  import os
11
- from typing import TYPE_CHECKING, Any, Self, cast
11
+ from typing import TYPE_CHECKING, Any, Self, assert_never, cast
12
12
 
13
13
  import anyenv
14
14
  import anyio
@@ -18,8 +18,6 @@ from clawd_code_sdk._internal.transport.subprocess_cli import SubprocessCLITrans
18
18
  from clawd_code_sdk.mcp_utils import process_mcp_request
19
19
  from clawd_code_sdk.models import (
20
20
  AskUserQuestionInput,
21
- ClaudeCodeServerInfo,
22
- ClaudeOAuthWaitForCompletionResponse,
23
21
  ControlErrorResponse,
24
22
  ControlResponse,
25
23
  JSONRPCError,
@@ -27,18 +25,12 @@ from clawd_code_sdk.models import (
27
25
  McpSdkServerConfigWithInstance,
28
26
  PermissionResultAllow,
29
27
  SDKControlElicitationRequest,
30
- SDKControlInitializeRequest,
31
- SDKControlInterruptRequest,
32
28
  SDKControlMcpMessageRequest,
33
29
  SDKControlPermissionRequest,
34
30
  SDKControlResponse,
35
- SDKControlRewindFilesRequest,
36
- SDKControlSetPermissionModeRequest,
37
- SDKControlStopTaskRequest,
38
31
  SDKHookCallbackRequest,
39
- SideQuestionResponse,
40
32
  ToolPermissionContext,
41
- control_request_adapter,
33
+ incoming_control_request_adapter,
42
34
  )
43
35
 
44
36
 
@@ -49,19 +41,17 @@ if TYPE_CHECKING:
49
41
 
50
42
  from clawd_code_sdk._internal.transport import Transport
51
43
  from clawd_code_sdk.models import (
52
- AgentDefinition,
53
44
  CanUseTool,
54
45
  ClaudeAgentOptions,
55
- ClaudeCodeAgentInfo,
56
- ControlRequestUnion,
57
46
  HookCallback,
58
47
  HookEvent,
59
48
  HookMatcher,
49
+ IncomingControlRequest,
60
50
  JSONRPCMessage,
61
51
  JSONRPCResponse,
62
52
  OnElicitation,
63
53
  OnUserQuestion,
64
- PermissionMode,
54
+ OutgoingControlRequest,
65
55
  PermissionResult,
66
56
  RequestId,
67
57
  )
@@ -94,13 +84,6 @@ class Query:
94
84
  on_elicitation: OnElicitation | None = None,
95
85
  hooks: dict[HookEvent, list[HookMatcher]] | None = None,
96
86
  sdk_mcp_servers: dict[str, McpServer] | None = None,
97
- initialize_timeout: float = 60.0,
98
- agents: dict[str, AgentDefinition] | None = None,
99
- system_prompt: str | None = None,
100
- append_system_prompt: str | None = None,
101
- json_schema: dict[str, Any] | None = None,
102
- prompt_suggestions: bool | None = None,
103
- agent_progress_summaries: bool | None = None,
104
87
  ):
105
88
  """Initialize Query with transport and callbacks.
106
89
 
@@ -111,15 +94,7 @@ class Query:
111
94
  on_elicitation: Optional callback for MCP elicitation requests
112
95
  hooks: Optional hook configurations
113
96
  sdk_mcp_servers: Optional SDK MCP server instances
114
- initialize_timeout: Timeout in seconds for the initialize request
115
- agents: Optional agent definitions to send via initialize
116
- system_prompt: Optional system prompt to send via initialize
117
- append_system_prompt: Optional text to append to preset system prompt
118
- json_schema: Optional JSON schema for structured output
119
- prompt_suggestions: Optional flag to enable prompt suggestions
120
- agent_progress_summaries: Optional flag to enable agent progress summaries
121
97
  """
122
- self._initialize_timeout = initialize_timeout
123
98
  self.transport = transport
124
99
  self.can_use_tool = can_use_tool
125
100
  self.on_user_question = on_user_question
@@ -129,12 +104,6 @@ class Query:
129
104
  for event, matchers in (hooks or {}).items()
130
105
  }
131
106
  self.sdk_mcp_servers = sdk_mcp_servers or {}
132
- self._agents = agents
133
- self._system_prompt = system_prompt
134
- self._append_system_prompt = append_system_prompt
135
- self._json_schema = json_schema
136
- self._prompt_suggestions = prompt_suggestions
137
- self._agent_progress_summaries = agent_progress_summaries
138
107
  # Control protocol state
139
108
  self.pending_control_responses: dict[str, anyio.Event] = {}
140
109
  self.pending_control_results: dict[str, dict[str, Any] | Exception] = {}
@@ -149,19 +118,12 @@ class Query:
149
118
  self._child_tasks: set[asyncio.Task[Any]] = set()
150
119
  self._inflight_requests: dict[str, asyncio.Task[Any]] = {}
151
120
  self._closed = False
152
- self._initialization_result: ClaudeCodeServerInfo | None = None
153
121
  # Track first result for proper stream closure with SDK MCP servers
154
122
  self._first_result_event = anyio.Event()
155
123
 
156
124
  @classmethod
157
125
  def from_options(cls, options: ClaudeAgentOptions, transport: Transport | None = None) -> Query:
158
- # Extract SDK MCP servers from options
159
- if options.instrument:
160
- from clawd_code_sdk.instrumentation import inject_tracing_hooks
161
-
162
- hooks = inject_tracing_hooks(options.hooks)
163
- else:
164
- hooks = options.hooks or {}
126
+ hooks = options.hooks or {}
165
127
 
166
128
  # If on_permission is a callback, extract it for Query and replace with
167
129
  # "stdio" so the CLI routes permission requests through the control protocol.
@@ -177,22 +139,6 @@ class Query:
177
139
  if isinstance(config, McpSdkServerConfigWithInstance):
178
140
  sdk_mcp_servers[name] = config.instance
179
141
 
180
- # Calculate initialize timeout from CLAUDE_CODE_STREAM_CLOSE_TIMEOUT env var if set
181
- # CLAUDE_CODE_STREAM_CLOSE_TIMEOUT is in milliseconds, convert to seconds
182
- initialize_timeout_ms = int(os.environ.get("CLAUDE_CODE_STREAM_CLOSE_TIMEOUT", "60000"))
183
- initialize_timeout = max(initialize_timeout_ms / 1000.0, 60.0)
184
- # Extract system prompt for initialize request
185
- system_prompt: str | None = None
186
- append_system_prompt: str | None = None
187
- if options.system_prompt is None:
188
- if not options.include_builtin_system_prompt:
189
- system_prompt = "" # Clear the builtin prompt
190
- # else: send nothing, CLI uses its default builtin prompt
191
- elif options.include_builtin_system_prompt:
192
- append_system_prompt = options.system_prompt
193
- else:
194
- system_prompt = options.system_prompt
195
-
196
142
  # Create Query to handle control protocol
197
143
  return cls(
198
144
  transport=transport or SubprocessCLITransport(options=options),
@@ -201,26 +147,17 @@ class Query:
201
147
  on_elicitation=options.on_elicitation,
202
148
  hooks=hooks,
203
149
  sdk_mcp_servers=sdk_mcp_servers,
204
- initialize_timeout=initialize_timeout,
205
- agents=options.agents,
206
- system_prompt=system_prompt,
207
- append_system_prompt=append_system_prompt,
208
- json_schema=options.get_json_schema(),
209
- prompt_suggestions=options.prompt_suggestions,
210
- agent_progress_summaries=options.agent_progress_summaries,
211
150
  )
212
151
 
213
- @property
214
- def initialized(self) -> bool:
215
- return self._initialization_result is not None
152
+ def build_hooks_config(self) -> dict[HookEvent, Any] | None:
153
+ """Register hook callbacks and return the hooks config for initialization.
216
154
 
217
- async def initialize(self) -> ClaudeCodeServerInfo:
218
- """Initialize control protocol.
155
+ Processes the raw hooks configuration, assigns callback IDs to each hook
156
+ callback, and stores them in the internal dispatch table.
219
157
 
220
158
  Returns:
221
- Parsed server info with supported commands and capabilities
159
+ Hooks configuration dict for the initialize request, or None if empty.
222
160
  """
223
- # Build hooks configuration for initialization
224
161
  hooks_config: dict[HookEvent, Any] = {}
225
162
  for event, matchers in self.hooks.items():
226
163
  if not matchers:
@@ -237,20 +174,7 @@ class Query:
237
174
  if matcher.get("timeout") is not None:
238
175
  matcher_cfg["timeout"] = matcher.get("timeout")
239
176
  hooks_config[event].append(matcher_cfg)
240
- request = SDKControlInitializeRequest(
241
- hooks=hooks_config or None,
242
- agents={name: i.to_wire_model() for name, i in (self._agents or {}).items()} or None,
243
- system_prompt=self._system_prompt,
244
- append_system_prompt=self._append_system_prompt,
245
- json_schema=self._json_schema,
246
- prompt_suggestions=self._prompt_suggestions,
247
- sdk_mcp_servers=list(self.sdk_mcp_servers.keys()) or None,
248
- agent_progress_summaries=self._agent_progress_summaries,
249
- ).model_dump(by_alias=True, exclude_none=True)
250
- # Use longer timeout for initialize since MCP servers may take time to start
251
- response = await self._send_control_request(request, timeout=self._initialize_timeout)
252
- self._initialization_result = ClaudeCodeServerInfo.model_validate(response)
253
- return self._initialization_result
177
+ return hooks_config or None
254
178
 
255
179
  async def start(self) -> None:
256
180
  """Start reading messages from transport."""
@@ -303,23 +227,19 @@ class Query:
303
227
  event.set()
304
228
  case {"type": "control_response"} as msg:
305
229
  logger.info("unhandled control message: %s", msg)
306
- case {"type": "control_request"}:
307
- req_id = message["request_id"]
308
- req = control_request_adapter.validate_python(message["request"])
309
- self._spawn_control_request_handler(
310
- req_id, self._handle_control_request(req_id, req)
311
- )
230
+ case {"type": "control_request", "request_id": req_id, "request": request}:
231
+ req = incoming_control_request_adapter.validate_python(request)
232
+ coro = self._handle_control_request(req_id, req)
233
+ self._spawn_control_request_handler(req_id, coro)
312
234
  case {"type": "control_cancel_request"}:
313
- cancel_id = message.get("request_id")
314
- if cancel_id:
315
- inflight = self._inflight_requests.pop(cancel_id, None)
316
- if inflight:
317
- inflight.cancel()
235
+ if (cancel_id := message.get("request_id")) and (
236
+ inflight := self._inflight_requests.pop(cancel_id, None)
237
+ ):
238
+ inflight.cancel()
318
239
  case {"type": "result"}:
319
240
  self._first_result_event.set()
320
241
  await self._message_send.send(message)
321
- case _:
322
- # Regular SDK messages go to the stream
242
+ case _: # Regular SDK messages go to the stream
323
243
  await self._message_send.send(message)
324
244
 
325
245
  except anyio.get_cancelled_exc_class():
@@ -342,7 +262,7 @@ class Query:
342
262
  async def _handle_control_request(
343
263
  self,
344
264
  request_id: str,
345
- request_data: ControlRequestUnion,
265
+ request_data: IncomingControlRequest,
346
266
  ) -> None:
347
267
  """Handle incoming control request from CLI."""
348
268
  response_data: dict[str, Any] = {}
@@ -358,14 +278,8 @@ class Query:
358
278
  response_data = {"mcp_response": mcp_resp}
359
279
  case SDKControlElicitationRequest() as req:
360
280
  response_data = await self._handle_elicitation_request(req)
361
- case (
362
- SDKControlInitializeRequest()
363
- | SDKControlSetPermissionModeRequest()
364
- | SDKControlRewindFilesRequest()
365
- | SDKControlStopTaskRequest()
366
- | SDKControlInterruptRequest() # No response data needed
367
- ):
368
- pass # Handled elsewhere
281
+ case _ as unreachable:
282
+ assert_never(unreachable)
369
283
  dct = ControlResponse(subtype="success", request_id=request_id, response=response_data)
370
284
  success_response = SDKControlResponse(type="control_response", response=dct)
371
285
  await self.write_json(success_response)
@@ -387,29 +301,15 @@ class Query:
387
301
  Dispatches AskUserQuestion to on_user_question if set,
388
302
  otherwise falls through to can_use_tool for backwards compatibility.
389
303
  """
390
- context = ToolPermissionContext(
391
- tool_use_id=req.tool_use_id,
392
- agent_id=req.agent_id,
393
- decision_reason=req.decision_reason,
394
- suggestions=req.permission_suggestions or [],
395
- blocked_path=req.blocked_path,
396
- title=req.title,
397
- display_name=req.display_name,
398
- description=req.description,
399
- )
400
-
304
+ context = ToolPermissionContext.from_permission_request(req)
401
305
  # Dispatch elicitation requests to dedicated callback if available
402
306
  if req.tool_name == "AskUserQuestion" and self.on_user_question:
403
307
  input_data = cast(AskUserQuestionInput, req.input)
404
308
  result = await self.on_user_question(input_data, context)
405
- if isinstance(result, PermissionResultAllow) and result.updated_input is None:
406
- result.updated_input = req.input
407
- return result
408
-
409
- if not self.can_use_tool:
410
- raise RuntimeError("canUseTool callback is not provided")
411
-
412
- result = await self.can_use_tool(req.tool_name, req.input, context)
309
+ else:
310
+ if not self.can_use_tool:
311
+ raise RuntimeError("canUseTool callback is not provided")
312
+ result = await self.can_use_tool(req.tool_name, req.input, context)
413
313
  if isinstance(result, PermissionResultAllow) and result.updated_input is None:
414
314
  result.updated_input = req.input
415
315
  return result
@@ -438,7 +338,7 @@ class Query:
438
338
  return {k.rstrip("_"): v for k, v in hook_output.items()}
439
339
 
440
340
  async def _send_control_request(
441
- self, request: dict[str, Any], timeout: float = 60.0
341
+ self, request: OutgoingControlRequest, timeout: float = 60.0
442
342
  ) -> dict[str, Any]:
443
343
  """Send control request to CLI and wait for response.
444
344
 
@@ -453,7 +353,11 @@ class Query:
453
353
  event = anyio.Event()
454
354
  self.pending_control_responses[request_id] = event
455
355
  # Build and send request
456
- control_request = {"type": "control_request", "request_id": request_id, "request": request}
356
+ control_request = {
357
+ "type": "control_request",
358
+ "request_id": request_id,
359
+ "request": request.model_dump(by_alias=True, exclude_none=True),
360
+ }
457
361
  await self.write_json(control_request)
458
362
  # Wait for response
459
363
  try:
@@ -471,7 +375,7 @@ class Query:
471
375
  except TimeoutError as e:
472
376
  self.pending_control_responses.pop(request_id, None)
473
377
  self.pending_control_results.pop(request_id, None)
474
- subtype = request.get("subtype")
378
+ subtype = request.subtype
475
379
  raise ControlRequestTimeoutError(
476
380
  f"Control request timeout: {subtype}", subtype=subtype
477
381
  ) from e
@@ -494,162 +398,11 @@ class Query:
494
398
  """
495
399
  if server_name not in self.sdk_mcp_servers:
496
400
  dct = JSONRPCError(code=-32601, message=f"Server '{server_name}' not found")
497
- return JSONRPCErrorResponse(
498
- jsonrpc="2.0", id=get_jsonrpc_request_id(message), error=dct
499
- )
401
+ id_ = get_jsonrpc_request_id(message)
402
+ return JSONRPCErrorResponse(jsonrpc="2.0", id=id_, error=dct)
500
403
  server = self.sdk_mcp_servers[server_name]
501
404
  return await process_mcp_request(message, server)
502
405
 
503
- async def supported_agents(self) -> list[ClaudeCodeAgentInfo]:
504
- """Get the list of available subagents for the current session."""
505
- if self._initialization_result is None:
506
- raise RuntimeError("Not initialized. Call initialize() first.")
507
- return self._initialization_result.agents
508
-
509
- async def get_mcp_status(self) -> dict[str, Any]:
510
- """Get current MCP server connection status."""
511
- return await self._send_control_request({"subtype": "mcp_status"})
512
-
513
- async def set_mcp_servers(self, servers: dict[str, dict[str, Any]]) -> dict[str, Any]:
514
- """Add, replace, or remove MCP servers dynamically."""
515
- return await self._send_control_request({"subtype": "mcp_set_servers", "servers": servers})
516
-
517
- async def mcp_reconnect(self, server_name: str) -> dict[str, Any]:
518
- """Reconnect to an MCP server."""
519
- req = {"subtype": "mcp_reconnect", "serverName": server_name}
520
- return await self._send_control_request(req)
521
-
522
- async def mcp_toggle(self, server_name: str, *, enabled: bool) -> dict[str, Any]:
523
- """Enable or disable an MCP server."""
524
- req = {"subtype": "mcp_toggle", "serverName": server_name, "enabled": enabled}
525
- return await self._send_control_request(req)
526
-
527
- async def set_max_thinking_tokens(self, max_thinking_tokens: int) -> dict[str, Any]:
528
- """Set the maximum number of thinking tokens."""
529
- req = {"subtype": "set_max_thinking_tokens", "max_thinking_tokens": max_thinking_tokens}
530
- return await self._send_control_request(req)
531
-
532
- async def interrupt(self) -> dict[str, Any]:
533
- """Send interrupt control request."""
534
- return await self._send_control_request({"subtype": "interrupt"})
535
-
536
- async def set_permission_mode(self, mode: PermissionMode) -> dict[str, Any]:
537
- """Change permission mode."""
538
- return await self._send_control_request({"subtype": "set_permission_mode", "mode": mode})
539
-
540
- async def set_model(self, model: str | None) -> dict[str, Any]:
541
- """Change the AI model."""
542
- return await self._send_control_request({"subtype": "set_model", "model": model})
543
-
544
- async def cancel_async_message(self, message_uuid: str) -> dict[str, Any]:
545
- """Drop a pending async user message from the command queue by uuid."""
546
- return await self._send_control_request(
547
- {"subtype": "cancel_async_message", "message_uuid": message_uuid}
548
- )
549
-
550
- async def stop_task(self, task_id: str) -> dict[str, Any]:
551
- """Stop a running task."""
552
- return await self._send_control_request({"subtype": "stop_task", "task_id": task_id})
553
-
554
- async def channel_enable(self, server_name: str) -> dict[str, Any]:
555
- """Enable MCP channel notifications for a marketplace plugin server."""
556
- req = {"subtype": "channel_enable", "serverName": server_name}
557
- return await self._send_control_request(req)
558
-
559
- async def end_session(self) -> dict[str, Any]:
560
- """End the current session."""
561
- return await self._send_control_request({"subtype": "end_session"})
562
-
563
- async def remote_control(self, *, enabled: bool) -> dict[str, Any]:
564
- """Toggle the remote control REPL bridge for external session access.
565
-
566
- When enabled, starts a bridge that allows remote clients to send prompts,
567
- permission responses, interrupts, and model changes into the session.
568
- The response includes ``session_url``, ``connect_url``, and
569
- ``environment_id`` when enabling.
570
- """
571
- req = {"subtype": "remote_control", "enabled": enabled}
572
- return await self._send_control_request(req)
573
-
574
- async def apply_flag_settings(self, settings: dict[str, Any]) -> dict[str, Any]:
575
- """Apply runtime flag settings."""
576
- req = {"subtype": "apply_flag_settings", "settings": settings}
577
- return await self._send_control_request(req)
578
-
579
- async def get_settings(self) -> dict[str, Any]:
580
- """Get the effective merged settings and raw per-source settings."""
581
- return await self._send_control_request({"subtype": "get_settings"})
582
-
583
- async def get_context_usage(self) -> dict[str, Any]:
584
- """Get a breakdown of current context window usage by category."""
585
- return await self._send_control_request({"subtype": "get_context_usage"})
586
-
587
- async def mcp_authenticate(self, server_name: str) -> dict[str, Any]:
588
- """Trigger OAuth authentication for an MCP server."""
589
- req = {"subtype": "mcp_authenticate", "serverName": server_name}
590
- return await self._send_control_request(req)
591
-
592
- async def mcp_clear_auth(self, server_name: str) -> dict[str, Any]:
593
- """Clear OAuth credentials for an MCP server."""
594
- req = {"subtype": "mcp_clear_auth", "serverName": server_name}
595
- return await self._send_control_request(req)
596
-
597
- async def mcp_oauth_callback_url(self, server_name: str, callback_url: str) -> dict[str, Any]:
598
- """Provide an OAuth redirect callback URL to complete an MCP server OAuth flow."""
599
- req = {
600
- "subtype": "mcp_oauth_callback_url",
601
- "serverName": server_name,
602
- "callbackUrl": callback_url,
603
- }
604
- return await self._send_control_request(req)
605
-
606
- async def claude_oauth_wait_for_completion(self) -> ClaudeOAuthWaitForCompletionResponse:
607
- """Wait for an in-progress Claude OAuth flow to complete.
608
-
609
- Returns account details (email, organization, subscriptionType, etc.)
610
- once the OAuth flow finishes.
611
- """
612
- data = await self._send_control_request({"subtype": "claude_oauth_wait_for_completion"})
613
- return ClaudeOAuthWaitForCompletionResponse.model_validate(data)
614
-
615
- async def side_question(self, question: str) -> SideQuestionResponse:
616
- """Send a side question to the model using the current conversation context.
617
-
618
- The model answers the question without it being added to the main
619
- conversation history.
620
-
621
- Args:
622
- question: The question to ask the model.
623
- """
624
- data = await self._send_control_request({"subtype": "side_question", "question": question})
625
- return SideQuestionResponse.model_validate(data)
626
-
627
- async def rewind_files(self, user_message_id: str) -> dict[str, Any]:
628
- """Rewind tracked files to their state at a specific user message.
629
-
630
- Requires file checkpointing to be enabled via the `enable_file_checkpointing` option.
631
-
632
- Args:
633
- user_message_id: UUID of the user message to rewind to
634
- """
635
- req = {"subtype": "rewind_files", "user_message_id": user_message_id}
636
- return await self._send_control_request(req)
637
-
638
- async def seed_read_state(self, path: str, mtime: int) -> None:
639
- """Seed the CLI's readFileState cache with a path+mtime entry.
640
-
641
- Use when the client observed a Read that has since been removed from context
642
- (e.g. by snip), so a subsequent Edit won't fail "file not read yet".
643
- If the file changed on disk since the given mtime, the seed is skipped
644
- and Edit will correctly require a fresh Read.
645
-
646
- Args:
647
- path: Path to the file that was previously Read
648
- mtime: File mtime (floored ms) at the time of the observed Read
649
- """
650
- req = {"subtype": "seed_read_state", "path": path, "mtime": mtime}
651
- await self._send_control_request(req)
652
-
653
406
  async def receive_messages(self) -> AsyncGenerator[dict[str, Any]]:
654
407
  """Receive SDK messages (not control messages)."""
655
408
  async for message in self._message_receive: