claude-agent-sdk 0.1.1__py3-none-any.whl → 0.1.3__py3-none-any.whl

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.

Potentially problematic release.


This version of claude-agent-sdk might be problematic. Click here for more details.

@@ -18,11 +18,14 @@ from .query import query
18
18
  from .types import (
19
19
  AgentDefinition,
20
20
  AssistantMessage,
21
+ BaseHookInput,
21
22
  CanUseTool,
22
23
  ClaudeAgentOptions,
23
24
  ContentBlock,
24
25
  HookCallback,
25
26
  HookContext,
27
+ HookInput,
28
+ HookJSONOutput,
26
29
  HookMatcher,
27
30
  McpSdkServerConfig,
28
31
  McpServerConfig,
@@ -32,8 +35,13 @@ from .types import (
32
35
  PermissionResultAllow,
33
36
  PermissionResultDeny,
34
37
  PermissionUpdate,
38
+ PostToolUseHookInput,
39
+ PreCompactHookInput,
40
+ PreToolUseHookInput,
35
41
  ResultMessage,
36
42
  SettingSource,
43
+ StopHookInput,
44
+ SubagentStopHookInput,
37
45
  SystemMessage,
38
46
  TextBlock,
39
47
  ThinkingBlock,
@@ -41,6 +49,7 @@ from .types import (
41
49
  ToolResultBlock,
42
50
  ToolUseBlock,
43
51
  UserMessage,
52
+ UserPromptSubmitHookInput,
44
53
  )
45
54
 
46
55
  # MCP Server Support
@@ -306,8 +315,18 @@ __all__ = [
306
315
  "PermissionResultAllow",
307
316
  "PermissionResultDeny",
308
317
  "PermissionUpdate",
318
+ # Hook support
309
319
  "HookCallback",
310
320
  "HookContext",
321
+ "HookInput",
322
+ "BaseHookInput",
323
+ "PreToolUseHookInput",
324
+ "PostToolUseHookInput",
325
+ "UserPromptSubmitHookInput",
326
+ "StopHookInput",
327
+ "SubagentStopHookInput",
328
+ "PreCompactHookInput",
329
+ "HookJSONOutput",
311
330
  "HookMatcher",
312
331
  # Agent support
313
332
  "AgentDefinition",
@@ -31,6 +31,25 @@ if TYPE_CHECKING:
31
31
  logger = logging.getLogger(__name__)
32
32
 
33
33
 
34
+ def _convert_hook_output_for_cli(hook_output: dict[str, Any]) -> dict[str, Any]:
35
+ """Convert Python-safe field names to CLI-expected field names.
36
+
37
+ The Python SDK uses `async_` and `continue_` to avoid keyword conflicts,
38
+ but the CLI expects `async` and `continue`. This function performs the
39
+ necessary conversion.
40
+ """
41
+ converted = {}
42
+ for key, value in hook_output.items():
43
+ # Convert Python-safe names to JavaScript names
44
+ if key == "async_":
45
+ converted["async"] = value
46
+ elif key == "continue_":
47
+ converted["continue"] = value
48
+ else:
49
+ converted[key] = value
50
+ return converted
51
+
52
+
34
53
  class Query:
35
54
  """Handles bidirectional control protocol on top of Transport.
36
55
 
@@ -195,6 +214,7 @@ class Query:
195
214
 
196
215
  if subtype == "can_use_tool":
197
216
  permission_request: SDKControlPermissionRequest = request_data # type: ignore[assignment]
217
+ original_input = permission_request["input"]
198
218
  # Handle tool permission request
199
219
  if not self.can_use_tool:
200
220
  raise Exception("canUseTool callback is not provided")
@@ -213,9 +233,14 @@ class Query:
213
233
 
214
234
  # Convert PermissionResult to expected dict format
215
235
  if isinstance(response, PermissionResultAllow):
216
- response_data = {"behavior": "allow"}
217
- if response.updated_input is not None:
218
- response_data["updatedInput"] = response.updated_input
236
+ response_data = {
237
+ "behavior": "allow",
238
+ "updatedInput": (
239
+ response.updated_input
240
+ if response.updated_input is not None
241
+ else original_input
242
+ ),
243
+ }
219
244
  if response.updated_permissions is not None:
220
245
  response_data["updatedPermissions"] = [
221
246
  permission.to_dict()
@@ -238,11 +263,13 @@ class Query:
238
263
  if not callback:
239
264
  raise Exception(f"No hook callback found for ID: {callback_id}")
240
265
 
241
- response_data = await callback(
266
+ hook_output = await callback(
242
267
  request_data.get("input"),
243
268
  request_data.get("tool_use_id"),
244
269
  {"signal": None}, # TODO: Add abort signal support
245
270
  )
271
+ # Convert Python-safe field names (async_, continue_) to CLI-expected names (async, continue)
272
+ response_data = _convert_hook_output_for_cli(hook_output)
246
273
 
247
274
  elif subtype == "mcp_message":
248
275
  # Handle SDK MCP request
@@ -1,3 +1,3 @@
1
1
  """Version information for claude-agent-sdk."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "0.1.3"
claude_agent_sdk/types.py CHANGED
@@ -157,35 +157,197 @@ HookEvent = (
157
157
  )
158
158
 
159
159
 
160
+ # Hook input types - strongly typed for each hook event
161
+ class BaseHookInput(TypedDict):
162
+ """Base hook input fields present across many hook events."""
163
+
164
+ session_id: str
165
+ transcript_path: str
166
+ cwd: str
167
+ permission_mode: NotRequired[str]
168
+
169
+
170
+ class PreToolUseHookInput(BaseHookInput):
171
+ """Input data for PreToolUse hook events."""
172
+
173
+ hook_event_name: Literal["PreToolUse"]
174
+ tool_name: str
175
+ tool_input: dict[str, Any]
176
+
177
+
178
+ class PostToolUseHookInput(BaseHookInput):
179
+ """Input data for PostToolUse hook events."""
180
+
181
+ hook_event_name: Literal["PostToolUse"]
182
+ tool_name: str
183
+ tool_input: dict[str, Any]
184
+ tool_response: Any
185
+
186
+
187
+ class UserPromptSubmitHookInput(BaseHookInput):
188
+ """Input data for UserPromptSubmit hook events."""
189
+
190
+ hook_event_name: Literal["UserPromptSubmit"]
191
+ prompt: str
192
+
193
+
194
+ class StopHookInput(BaseHookInput):
195
+ """Input data for Stop hook events."""
196
+
197
+ hook_event_name: Literal["Stop"]
198
+ stop_hook_active: bool
199
+
200
+
201
+ class SubagentStopHookInput(BaseHookInput):
202
+ """Input data for SubagentStop hook events."""
203
+
204
+ hook_event_name: Literal["SubagentStop"]
205
+ stop_hook_active: bool
206
+
207
+
208
+ class PreCompactHookInput(BaseHookInput):
209
+ """Input data for PreCompact hook events."""
210
+
211
+ hook_event_name: Literal["PreCompact"]
212
+ trigger: Literal["manual", "auto"]
213
+ custom_instructions: str | None
214
+
215
+
216
+ # Union type for all hook inputs
217
+ HookInput = (
218
+ PreToolUseHookInput
219
+ | PostToolUseHookInput
220
+ | UserPromptSubmitHookInput
221
+ | StopHookInput
222
+ | SubagentStopHookInput
223
+ | PreCompactHookInput
224
+ )
225
+
226
+
227
+ # Hook-specific output types
228
+ class PreToolUseHookSpecificOutput(TypedDict):
229
+ """Hook-specific output for PreToolUse events."""
230
+
231
+ hookEventName: Literal["PreToolUse"]
232
+ permissionDecision: NotRequired[Literal["allow", "deny", "ask"]]
233
+ permissionDecisionReason: NotRequired[str]
234
+ updatedInput: NotRequired[dict[str, Any]]
235
+
236
+
237
+ class PostToolUseHookSpecificOutput(TypedDict):
238
+ """Hook-specific output for PostToolUse events."""
239
+
240
+ hookEventName: Literal["PostToolUse"]
241
+ additionalContext: NotRequired[str]
242
+
243
+
244
+ class UserPromptSubmitHookSpecificOutput(TypedDict):
245
+ """Hook-specific output for UserPromptSubmit events."""
246
+
247
+ hookEventName: Literal["UserPromptSubmit"]
248
+ additionalContext: NotRequired[str]
249
+
250
+
251
+ class SessionStartHookSpecificOutput(TypedDict):
252
+ """Hook-specific output for SessionStart events."""
253
+
254
+ hookEventName: Literal["SessionStart"]
255
+ additionalContext: NotRequired[str]
256
+
257
+
258
+ HookSpecificOutput = (
259
+ PreToolUseHookSpecificOutput
260
+ | PostToolUseHookSpecificOutput
261
+ | UserPromptSubmitHookSpecificOutput
262
+ | SessionStartHookSpecificOutput
263
+ )
264
+
265
+
160
266
  # See https://docs.anthropic.com/en/docs/claude-code/hooks#advanced%3A-json-output
161
- # for documentation of the output types. Currently, "continue", "stopReason",
162
- # and "suppressOutput" are not supported in the Python SDK.
163
- class HookJSONOutput(TypedDict):
164
- # Whether to block the action related to the hook.
267
+ # for documentation of the output types.
268
+ #
269
+ # IMPORTANT: The Python SDK uses `async_` and `continue_` (with underscores) to avoid
270
+ # Python keyword conflicts. These fields are automatically converted to `async` and
271
+ # `continue` when sent to the CLI. You should use the underscore versions in your
272
+ # Python code.
273
+ class AsyncHookJSONOutput(TypedDict):
274
+ """Async hook output that defers hook execution.
275
+
276
+ Fields:
277
+ async_: Set to True to defer hook execution. Note: This is converted to
278
+ "async" when sent to the CLI - use "async_" in your Python code.
279
+ asyncTimeout: Optional timeout in milliseconds for the async operation.
280
+ """
281
+
282
+ async_: Literal[
283
+ True
284
+ ] # Using async_ to avoid Python keyword (converted to "async" for CLI)
285
+ asyncTimeout: NotRequired[int]
286
+
287
+
288
+ class SyncHookJSONOutput(TypedDict):
289
+ """Synchronous hook output with control and decision fields.
290
+
291
+ This defines the structure for hook callbacks to control execution and provide
292
+ feedback to Claude.
293
+
294
+ Common Control Fields:
295
+ continue_: Whether Claude should proceed after hook execution (default: True).
296
+ Note: This is converted to "continue" when sent to the CLI.
297
+ suppressOutput: Hide stdout from transcript mode (default: False).
298
+ stopReason: Message shown when continue is False.
299
+
300
+ Decision Fields:
301
+ decision: Set to "block" to indicate blocking behavior.
302
+ systemMessage: Warning message displayed to the user.
303
+ reason: Feedback message for Claude about the decision.
304
+
305
+ Hook-Specific Output:
306
+ hookSpecificOutput: Event-specific controls (e.g., permissionDecision for
307
+ PreToolUse, additionalContext for PostToolUse).
308
+
309
+ Note: The CLI documentation shows field names without underscores ("async", "continue"),
310
+ but Python code should use the underscore versions ("async_", "continue_") as they
311
+ are automatically converted.
312
+ """
313
+
314
+ # Common control fields
315
+ continue_: NotRequired[
316
+ bool
317
+ ] # Using continue_ to avoid Python keyword (converted to "continue" for CLI)
318
+ suppressOutput: NotRequired[bool]
319
+ stopReason: NotRequired[str]
320
+
321
+ # Decision fields
322
+ # Note: "approve" is deprecated for PreToolUse (use permissionDecision instead)
323
+ # For other hooks, only "block" is meaningful
165
324
  decision: NotRequired[Literal["block"]]
166
- # Optionally add a system message that is not visible to Claude but saved in
167
- # the chat transcript.
168
325
  systemMessage: NotRequired[str]
169
- # See each hook's individual "Decision Control" section in the documentation
170
- # for guidance.
171
- hookSpecificOutput: NotRequired[Any]
326
+ reason: NotRequired[str]
172
327
 
328
+ # Hook-specific outputs
329
+ hookSpecificOutput: NotRequired[HookSpecificOutput]
173
330
 
174
- @dataclass
175
- class HookContext:
176
- """Context information for hook callbacks."""
177
331
 
178
- signal: Any | None = None # Future: abort signal support
332
+ HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput
333
+
334
+
335
+ class HookContext(TypedDict):
336
+ """Context information for hook callbacks.
337
+
338
+ Fields:
339
+ signal: Reserved for future abort signal support. Currently always None.
340
+ """
341
+
342
+ signal: Any | None # Future: abort signal support
179
343
 
180
344
 
181
345
  HookCallback = Callable[
182
346
  # HookCallback input parameters:
183
- # - input
184
- # See https://docs.anthropic.com/en/docs/claude-code/hooks#hook-input for
185
- # the type of 'input', the first value.
186
- # - tool_use_id
187
- # - context
188
- [dict[str, Any], str | None, HookContext],
347
+ # - input: Strongly-typed hook input with discriminated unions based on hook_event_name
348
+ # - tool_use_id: Optional tool use identifier
349
+ # - context: Hook context with abort signal support (currently placeholder)
350
+ [HookInput, str | None, HookContext],
189
351
  Awaitable[HookJSONOutput],
190
352
  ]
191
353
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: claude-agent-sdk
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Summary: Python SDK for Claude Code
5
5
  Project-URL: Homepage, https://github.com/anthropics/claude-agent-sdk-python
6
6
  Project-URL: Documentation, https://docs.anthropic.com/en/docs/claude-code/sdk
@@ -1,17 +1,17 @@
1
- claude_agent_sdk/__init__.py,sha256=ZwJ2YpPdvDRdg1j73TGmK5FEfriv00MbgB5GbEkgqEs,11584
1
+ claude_agent_sdk/__init__.py,sha256=6bpu7xdAzyHRRgxdXGBFbZgS-sVq2bvC7s2Z_whog7c,12035
2
2
  claude_agent_sdk/_errors.py,sha256=nSdJNNeszvXG1PfnXd2sQpVNORqMct-MfPaiM3XeJL4,1579
3
- claude_agent_sdk/_version.py,sha256=yIo_daGf7IiorFxtDROWUbETCsox9r8uyNEv2NuZUfQ,71
3
+ claude_agent_sdk/_version.py,sha256=E5buSXiVJIZpoi3ylyUDKfQutllqoNUPcsm7cW4lC70,71
4
4
  claude_agent_sdk/client.py,sha256=Bye3QKb-iTg6Yq34ZPGHzaMg1isT9RvyHs5TkC2jWDI,13926
5
5
  claude_agent_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
6
  claude_agent_sdk/query.py,sha256=WebhztsMZPdaxyy1LBEZv4_j23vjp_ceX9DtrBsZqCA,4530
7
- claude_agent_sdk/types.py,sha256=0GcWj57sqRqh7Rv3UXm8uTQkH9ENMr4AdDsm8_cUY7g,11841
7
+ claude_agent_sdk/types.py,sha256=0CJP14sf1PJm1NdpLYvFQ_8bUrtuQMWaOPHsmvxB040,16646
8
8
  claude_agent_sdk/_internal/__init__.py,sha256=zDdgjqp8SI9mTnwZbP2Be-w4LWlv4a3kA-TS2i75jsM,39
9
9
  claude_agent_sdk/_internal/client.py,sha256=Z06Fj4t5mHkKHKBUwxmHMTEo7lzs3X4_D_c-xq6Wg4I,4603
10
10
  claude_agent_sdk/_internal/message_parser.py,sha256=xxpOU3E8X21FCoy2OtLWKfEQr3AFYM454qJt6Xa0tmc,6475
11
- claude_agent_sdk/_internal/query.py,sha256=b1JhWIKEIanVEA6g8SRqaYVVBsXjHWp-6rQXhIw8z70,20961
11
+ claude_agent_sdk/_internal/query.py,sha256=mfSiIfs58U1LYMnbj5GeLATvdI_cRVIxStV1He-cMTE,22015
12
12
  claude_agent_sdk/_internal/transport/__init__.py,sha256=sv8Iy1b9YmPlXu4XsdN98gJIlyrLtwq8PKQyF4qnQLk,1978
13
13
  claude_agent_sdk/_internal/transport/subprocess_cli.py,sha256=ViZxmHoAx3NdFNgLUFgNYuCjJZdVqKk2sxHlB57Z2ng,19097
14
- claude_agent_sdk-0.1.1.dist-info/METADATA,sha256=rNgqZ08Pq6tKo9n13C3d_R8EwdHZcqnP7vAiGHDJm5w,9648
15
- claude_agent_sdk-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
- claude_agent_sdk-0.1.1.dist-info/licenses/LICENSE,sha256=zr3eio-57lnl6q7RlXi_gIWqcEdWIlnDHzjyJcJvaBI,1070
17
- claude_agent_sdk-0.1.1.dist-info/RECORD,,
14
+ claude_agent_sdk-0.1.3.dist-info/METADATA,sha256=UieBXMnHeT5-bVpX8aJWQtph4MtLpf4hL8O-vL1up-8,9648
15
+ claude_agent_sdk-0.1.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
+ claude_agent_sdk-0.1.3.dist-info/licenses/LICENSE,sha256=zr3eio-57lnl6q7RlXi_gIWqcEdWIlnDHzjyJcJvaBI,1070
17
+ claude_agent_sdk-0.1.3.dist-info/RECORD,,