clawd-code-sdk 1.2.0__tar.gz → 1.2.2__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 (93) hide show
  1. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/PKG-INFO +2 -2
  2. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/pyproject.toml +14 -26
  3. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_errors.py +15 -13
  4. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/query.py +1 -1
  5. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/transport/subprocess_cli.py +24 -19
  6. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/client.py +2 -2
  7. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/instrumentation.py +2 -2
  8. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/mcp_utils.py +1 -1
  9. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/input_types.py +1 -1
  10. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/prompts.py +13 -5
  11. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/system_messages.py +2 -0
  12. clawd_code_sdk-1.2.2/tests/test_transport_close.py +84 -0
  13. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/.gitignore +0 -0
  14. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/LICENSE +0 -0
  15. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/README.md +0 -0
  16. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/__init__.py +0 -0
  17. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_bundled/.gitignore +0 -0
  18. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/__init__.py +0 -0
  19. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/mcp_compat.py +0 -0
  20. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/sdk_mcp_bridge.py +0 -0
  21. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/session_mutations.py +0 -0
  22. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/sessions.py +0 -0
  23. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/transport/__init__.py +0 -0
  24. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_internal/transport/subprocess_utils.py +0 -0
  25. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/_version.py +0 -0
  26. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/anthropic_stream.py +0 -0
  27. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/list_sessions.py +0 -0
  28. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/__init__.py +0 -0
  29. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/agents.py +0 -0
  30. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/anthropic_types.py +0 -0
  31. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/base.py +0 -0
  32. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/content_blocks.py +0 -0
  33. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/context_usage.py +0 -0
  34. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/control.py +0 -0
  35. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/hooks.py +0 -0
  36. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/mcp.py +0 -0
  37. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/messages.py +0 -0
  38. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/options.py +0 -0
  39. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/output_types.py +0 -0
  40. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/permissions.py +0 -0
  41. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/prompt_requests.py +0 -0
  42. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/server_info.py +0 -0
  43. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/session.py +0 -0
  44. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/settings.py +0 -0
  45. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/thinking.py +0 -0
  46. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/models/usage.py +0 -0
  47. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/py.typed +0 -0
  48. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/session.py +0 -0
  49. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/storage/ARCHITECTURE.md +0 -0
  50. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/storage/__init__.py +0 -0
  51. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/storage/helpers.py +0 -0
  52. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/storage/models.py +0 -0
  53. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/storage/replay.py +0 -0
  54. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/src/clawd_code_sdk/usage.py +0 -0
  55. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/__init__.py +0 -0
  56. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/conftest.py +0 -0
  57. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/__init__.py +0 -0
  58. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_agents_and_settings.py +0 -0
  59. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_dynamic_control.py +0 -0
  60. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_hook_events.py +0 -0
  61. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_hooks.py +0 -0
  62. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_include_partial_messages.py +0 -0
  63. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_mcp_resources.py +0 -0
  64. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_mcp_tools.py +0 -0
  65. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_sdk_mcp_resources.py +0 -0
  66. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_sdk_mcp_tools.py +0 -0
  67. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_slash_commands.py +0 -0
  68. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_stderr_callback.py +0 -0
  69. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_storage_parsing.py +0 -0
  70. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_structured_output.py +0 -0
  71. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_subagent_invocation.py +0 -0
  72. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/e2e/test_tool_permissions.py +0 -0
  73. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/mcp_server.py +0 -0
  74. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/mock_claude_server.py +0 -0
  75. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_changelog.py +0 -0
  76. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_client.py +0 -0
  77. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_elicitation_mcp_conversion.py +0 -0
  78. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_errors.py +0 -0
  79. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_image.png +0 -0
  80. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_integration.py +0 -0
  81. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_line_framing.py +0 -0
  82. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_message_parser.py +0 -0
  83. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_result_error.py +0 -0
  84. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_sandbox_settings.py +0 -0
  85. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_sdk_0_3_types.py +0 -0
  86. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_sdk_mcp_integration.py +0 -0
  87. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_session.py +0 -0
  88. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_session_mutations.py +0 -0
  89. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_sessions.py +0 -0
  90. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_streaming_client.py +0 -0
  91. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_subprocess_buffering.py +0 -0
  92. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_tool_callbacks.py +0 -0
  93. {clawd_code_sdk-1.2.0 → clawd_code_sdk-1.2.2}/tests/test_transport.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: clawd-code-sdk
3
- Version: 1.2.0
3
+ Version: 1.2.2
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
@@ -27,12 +27,12 @@ Requires-Dist: python-dotenv>=1.2.1
27
27
  Provides-Extra: dev
28
28
  Requires-Dist: anyio[trio]>=4.0.0; extra == 'dev'
29
29
  Requires-Dist: fastmcp>=3.0.0; extra == 'dev'
30
- Requires-Dist: mypy>=1.0.0; extra == 'dev'
31
30
  Requires-Dist: pytest-asyncio>=0.20.0; extra == 'dev'
32
31
  Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
33
32
  Requires-Dist: pytest-timeout>=2.4.0; extra == 'dev'
34
33
  Requires-Dist: pytest>=7.0.0; extra == 'dev'
35
34
  Requires-Dist: ruff>=0.1.0; extra == 'dev'
35
+ Requires-Dist: ty; extra == 'dev'
36
36
  Requires-Dist: types-jsonschema>=4.20.0; extra == 'dev'
37
37
  Provides-Extra: otel
38
38
  Requires-Dist: opentelemetry-api>=1.20.0; extra == 'otel'
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "clawd-code-sdk"
3
- version = "1.2.0"
3
+ version = "1.2.2"
4
4
  description = "Python SDK for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -40,7 +40,7 @@ dev = [
40
40
  "anyio[trio]>=4.0.0",
41
41
  "pytest-cov>=4.0.0",
42
42
  "pytest-timeout>=2.4.0",
43
- "mypy>=1.0.0",
43
+ "ty",
44
44
  "ruff>=0.1.0",
45
45
  "fastmcp>=3.0.0",
46
46
  "types-jsonschema>=4.20.0",
@@ -65,23 +65,6 @@ include = [
65
65
  "/LICENSE",
66
66
  ]
67
67
 
68
- [tool.mypy]
69
- python_version = "3.13"
70
- strict = true
71
- exclude = ["examples/"]
72
- warn_return_any = true
73
- warn_unused_configs = true
74
- disallow_untyped_defs = true
75
- disallow_incomplete_defs = true
76
- check_untyped_defs = true
77
- disallow_untyped_decorators = true
78
- no_implicit_optional = true
79
- warn_redundant_casts = true
80
- warn_unused_ignores = true
81
- warn_no_return = true
82
- warn_unreachable = true
83
- strict_equality = true
84
-
85
68
  [tool.pytest]
86
69
  addopts = ["-m", "not slow and not acp_snapshot and not e2e"]
87
70
  filterwarnings = ["ignore::DeprecationWarning:pydantic.*:"]
@@ -112,7 +95,7 @@ exclude = ["examples/"]
112
95
  future-annotations = true
113
96
  select = [
114
97
  "A", # Flake8-builtins
115
- # "ANN", # Flake8-Annotations
98
+ "ANN", # Flake8-Annotations (enforces complete annotations; ty does not)
116
99
  # "ASYNC", # Flake8-Async
117
100
  # "ARG", # # Flake8-Unused-Arguments
118
101
  "B", # flake8-bugbear
@@ -172,6 +155,7 @@ select = [
172
155
  "YTT", # flake8-2020
173
156
  ]
174
157
  ignore = [
158
+ "ANN401", # Dynamically typed expressions (Any) are allowed
175
159
  "BLE001",
176
160
  "C408", # Unnecessary {obj_type} call (rewrite as a literal)
177
161
  "C901", # {name} is too complex ({complexity} > {max_complexity})
@@ -239,21 +223,25 @@ max-complexity = 15
239
223
 
240
224
  [tool.ruff.lint.per-file-ignores]
241
225
  "__init__.py" = ["E402", "I001"]
242
- "scripts/*" = ["INP001", "PLR2004"]
243
- "*tests/*" = ["D100", "PLR2004"]
226
+ "scripts/*" = ["INP001", "PLR2004", "ANN"]
227
+ "*tests/*" = ["D100", "PLR2004", "ANN"] # tests need not be fully annotated
228
+ "duties.py" = ["ANN"] # tooling, not package code
244
229
  "src/clawd_code_sdk/models/settings.py" = ["ALL"]
245
230
  "docs/examples/**/*.py" = [
246
231
  "TC001",
247
232
  ] # Examples don't need TYPE_CHECKING imports
248
233
 
234
+ [tool.ty.src]
235
+ # `ty check` (hooks, CI, editors) type-checks the package code only.
236
+ include = ["src"]
237
+
249
238
  [tool.ty.environment]
250
239
  python-version = "3.13"
251
240
  python-platform = "all"
252
241
 
253
242
  [tool.ty.rules]
254
- unresolved-import = "ignore"
255
- unused-type-ignore-comment = "ignore"
256
- invalid-type-form = "ignore"
257
- not-subscriptable = "ignore"
243
+ # Narrowing an overridden class attribute (e.g. pydantic discriminators,
244
+ # `Config` attributes) is an intentional pattern.
245
+ incompatible-mutable-override = "ignore"
258
246
  possibly-missing-import = "warn"
259
247
  division-by-zero = "warn"
@@ -20,7 +20,7 @@ class CLIConnectionError(ClaudeSDKError):
20
20
  class CLINotFoundError(CLIConnectionError):
21
21
  """Raised when Claude Code is not found or not installed."""
22
22
 
23
- def __init__(self, message: str = "Claude Code not found", cli_path: str | None = None):
23
+ def __init__(self, message: str = "Claude Code not found", cli_path: str | None = None) -> None:
24
24
  if cli_path:
25
25
  message = f"{message}: {cli_path}"
26
26
  super().__init__(message)
@@ -29,7 +29,9 @@ class CLINotFoundError(CLIConnectionError):
29
29
  class ProcessError(ClaudeSDKError):
30
30
  """Raised when the CLI process fails."""
31
31
 
32
- def __init__(self, message: str, exit_code: int | None = None, stderr: str | None = None):
32
+ def __init__(
33
+ self, message: str, exit_code: int | None = None, stderr: str | None = None
34
+ ) -> None:
33
35
  self.exit_code = exit_code
34
36
  self.stderr = stderr
35
37
 
@@ -50,7 +52,7 @@ class ResultError(ProcessError):
50
52
  ``ProcessError`` so existing handlers keep catching it. (Upstream #1198/#1205.)
51
53
  """
52
54
 
53
- def __init__(self, message: str, data: dict[str, Any], exit_code: int | None = None):
55
+ def __init__(self, message: str, data: dict[str, Any], exit_code: int | None = None) -> None:
54
56
  self.data = data
55
57
  super().__init__(message, exit_code=exit_code)
56
58
 
@@ -86,7 +88,7 @@ def error_result_text(message: dict[str, Any]) -> str:
86
88
  class CLIJSONDecodeError(ClaudeSDKError):
87
89
  """Raised when unable to decode JSON from CLI output."""
88
90
 
89
- def __init__(self, line: str, original_error: Exception):
91
+ def __init__(self, line: str, original_error: Exception) -> None:
90
92
  self.line = line
91
93
  self.original_error = original_error
92
94
  super().__init__(f"Failed to decode JSON: {line[:100]}...")
@@ -95,7 +97,7 @@ class CLIJSONDecodeError(ClaudeSDKError):
95
97
  class MessageParseError(ClaudeSDKError):
96
98
  """Raised when unable to parse a message from CLI output."""
97
99
 
98
- def __init__(self, message: str, data: dict[str, Any] | None = None):
100
+ def __init__(self, message: str, data: dict[str, Any] | None = None) -> None:
99
101
  self.data = data
100
102
  super().__init__(f"{message}: {data}")
101
103
 
@@ -137,7 +139,7 @@ class APIError(ClaudeSDKError):
137
139
  message: str,
138
140
  error_type: APIErrorType,
139
141
  model: Model | None = None,
140
- ):
142
+ ) -> None:
141
143
  self.error_type = error_type
142
144
  self.model = model
143
145
  super().__init__(message)
@@ -149,7 +151,7 @@ class AuthenticationError(APIError):
149
151
  This typically indicates an invalid API key or insufficient permissions.
150
152
  """
151
153
 
152
- def __init__(self, message: str, model: Model | None = None):
154
+ def __init__(self, message: str, model: Model | None = None) -> None:
153
155
  super().__init__(message, "authentication_failed", model)
154
156
 
155
157
 
@@ -160,7 +162,7 @@ class BillingError(APIError):
160
162
  billing-related issues.
161
163
  """
162
164
 
163
- def __init__(self, message: str, model: Model | None = None):
165
+ def __init__(self, message: str, model: Model | None = None) -> None:
164
166
  super().__init__(message, "billing_error", model)
165
167
 
166
168
 
@@ -171,7 +173,7 @@ class RateLimitError(APIError):
171
173
  when handling this exception.
172
174
  """
173
175
 
174
- def __init__(self, message: str, model: Model | None = None):
176
+ def __init__(self, message: str, model: Model | None = None) -> None:
175
177
  super().__init__(message, "rate_limit", model)
176
178
 
177
179
 
@@ -182,7 +184,7 @@ class InvalidRequestError(APIError):
182
184
  Check the error message for details about what needs to be corrected.
183
185
  """
184
186
 
185
- def __init__(self, message: str, model: Model | None = None):
187
+ def __init__(self, message: str, model: Model | None = None) -> None:
186
188
  super().__init__(message, "invalid_request", model)
187
189
 
188
190
 
@@ -193,14 +195,14 @@ class ServerError(APIError):
193
195
  Applications should implement retry logic for transient server errors.
194
196
  """
195
197
 
196
- def __init__(self, message: str, model: Model | None = None):
198
+ def __init__(self, message: str, model: Model | None = None) -> None:
197
199
  super().__init__(message, "server_error", model)
198
200
 
199
201
 
200
202
  class ControlRequestError(ClaudeSDKError):
201
203
  """Raised when a control protocol request fails."""
202
204
 
203
- def __init__(self, message: str, subtype: str | None = None):
205
+ def __init__(self, message: str, subtype: str | None = None) -> None:
204
206
  self.subtype = subtype
205
207
  super().__init__(message)
206
208
 
@@ -224,7 +226,7 @@ class McpError(ControlRequestError):
224
226
  error_code: int | None = None,
225
227
  server_name: str | None = None,
226
228
  subtype: str | None = None,
227
- ):
229
+ ) -> None:
228
230
  self.error_code = error_code
229
231
  self.server_name = server_name
230
232
  super().__init__(message, subtype=subtype)
@@ -93,7 +93,7 @@ class Query:
93
93
  on_elicitation: OnElicitation | None = None,
94
94
  hooks: dict[HookEvent, list[HookMatcher]] | None = None,
95
95
  sdk_mcp_servers: dict[str, McpServer] | None = None,
96
- ):
96
+ ) -> None:
97
97
  """Initialize Query with transport and callbacks.
98
98
 
99
99
  Args:
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
5
6
  import atexit
6
7
  from contextlib import suppress
7
8
  import logging
@@ -63,14 +64,14 @@ atexit.register(_kill_active_children)
63
64
  class SubprocessCLITransport(Transport):
64
65
  """Subprocess transport using Claude Code CLI."""
65
66
 
66
- def __init__(self, options: ClaudeAgentOptions | None = None):
67
+ def __init__(self, options: ClaudeAgentOptions | None = None) -> None:
67
68
  self._options = options or ClaudeAgentOptions()
68
69
  self._cli_path = str(opts) if (opts := self._options.cli_path) is not None else None
69
70
  self._process: Process | None = None
70
71
  self._stdout_stream: TextReceiveStream | None = None
71
72
  self._stdin_stream: TextSendStream | None = None
72
73
  self._stderr_stream: TextReceiveStream | None = None
73
- self._stderr_task_group: anyio.abc.TaskGroup | None = None
74
+ self._stderr_task: asyncio.Task[None] | None = None
74
75
  self._ready = False
75
76
  self._exit_error: Exception | None = None # Track process exit errors
76
77
  self._max_buffer_size = self._options.max_buffer_size or _DEFAULT_MAX_BUFFER_SIZE
@@ -161,10 +162,11 @@ class SubprocessCLITransport(Transport):
161
162
  # Setup stderr stream if piped
162
163
  if self._process.stderr:
163
164
  self._stderr_stream = TextReceiveStream(self._process.stderr, errors="replace")
164
- # Start async task to read stderr
165
- self._stderr_task_group = anyio.create_task_group()
166
- await self._stderr_task_group.__aenter__()
167
- self._stderr_task_group.start_soon(self._handle_stderr)
165
+ # Read stderr in a standalone task. A task group entered here and
166
+ # exited in close()/read_messages() would span two call sites (and
167
+ # possibly two tasks), and cancelling its scope would cancel the
168
+ # caller itself.
169
+ self._stderr_task = asyncio.get_running_loop().create_task(self._handle_stderr())
168
170
 
169
171
  # Setup stdin for streaming (always used now)
170
172
  if self._process.stdin:
@@ -226,6 +228,17 @@ class SubprocessCLITransport(Transport):
226
228
  # cancellation unwind.
227
229
  emit(framer.flush())
228
230
 
231
+ async def _stop_stderr_reader(self, grace: float) -> None:
232
+ """Stop the stderr reader task, giving it ``grace`` seconds to finish on its own."""
233
+ task, self._stderr_task = self._stderr_task, None
234
+ if task is None:
235
+ return
236
+ if not task.done() and grace > 0:
237
+ await asyncio.wait({task}, timeout=grace)
238
+ if not task.done():
239
+ task.cancel()
240
+ await asyncio.wait({task})
241
+
229
242
  async def close(self) -> None:
230
243
  """Close the transport and clean up resources.
231
244
 
@@ -248,12 +261,8 @@ class SubprocessCLITransport(Transport):
248
261
 
249
262
  process = self._process
250
263
  with anyio.CancelScope(shield=True):
251
- # Close stderr task group if active
252
- if self._stderr_task_group:
253
- with suppress(Exception):
254
- self._stderr_task_group.cancel_scope.cancel()
255
- await self._stderr_task_group.__aexit__(None, None, None)
256
- self._stderr_task_group = None
264
+ # Stop the stderr reader (it flushes its last partial line on cancel)
265
+ await self._stop_stderr_reader(grace=0)
257
266
 
258
267
  # Close stdin stream (hold the write lock to prevent a race with
259
268
  # concurrent writes). Bounded: a writer blocked on a full stdin pipe
@@ -361,13 +370,9 @@ class SubprocessCLITransport(Transport):
361
370
  except Exception:
362
371
  returncode = -1
363
372
 
364
- # Wait for stderr reader to finish draining
365
- if self._stderr_task_group:
366
- with suppress(Exception):
367
- with anyio.move_on_after(5):
368
- self._stderr_task_group.cancel_scope.cancel()
369
- await self._stderr_task_group.__aexit__(None, None, None)
370
- self._stderr_task_group = None
373
+ # The process has exited, so stderr reaches EOF shortly: let the reader
374
+ # drain what is left before stopping it.
375
+ await self._stop_stderr_reader(grace=5)
371
376
 
372
377
  # Use exit code for error detection
373
378
  if returncode:
@@ -147,7 +147,7 @@ class ClaudeSDKClient:
147
147
  self,
148
148
  options: ClaudeAgentOptions | None = None,
149
149
  transport: Transport | None = None,
150
- ):
150
+ ) -> None:
151
151
  """Initialize Claude SDK client."""
152
152
  options = options or ClaudeAgentOptions()
153
153
  self.options = options
@@ -783,7 +783,7 @@ class ClaudeSDKClient:
783
783
  input_messages: list[ChatMessage] = []
784
784
  if prompt := self._logfire_prompt:
785
785
  part = TextPart(type="text", content=prompt)
786
- input_messages = [ChatMessage(role="user", parts=[part])] # ty:ignore[invalid-argument-type]
786
+ input_messages = [ChatMessage(role="user", parts=[part])]
787
787
 
788
788
  span_data: dict[str, Any] = {
789
789
  OPERATION_NAME: "invoke_agent",
@@ -63,7 +63,7 @@ class ConversationState:
63
63
  part = ToolCallResponsePart(
64
64
  type="tool_call_response", id=tool_use_id, name=tool_name, response=result
65
65
  )
66
- msg = ChatMessage(role="tool", parts=[part]) # ty:ignore[invalid-argument-type]
66
+ msg = ChatMessage(role="tool", parts=[part])
67
67
  self._history.append(msg)
68
68
 
69
69
  def open_chat_span(self) -> None:
@@ -114,7 +114,7 @@ class ConversationState:
114
114
  self._current_span.set_attribute(REQUEST_MODEL, model)
115
115
  self._current_span.set_attribute(RESPONSE_MODEL, model)
116
116
  self._current_span.message = f"chat {model}"
117
- self._current_span.update_name(f"chat {model}") # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]
117
+ self._current_span.update_name(f"chat {model}") # ty: ignore[missing-attribute]
118
118
  if error := message.error:
119
119
  self._current_span.set_attribute(ERROR_TYPE, str(error))
120
120
  self._current_span.set_level("error")
@@ -234,7 +234,7 @@ def build_input_schema(input_schema: type | dict[str, Any]) -> dict[str, Any]:
234
234
  case type() as tp:
235
235
  return TypeAdapter(tp).json_schema()
236
236
  case _ as unreachable:
237
- assert_never(unreachable) # ty:ignore[type-assertion-failure]
237
+ assert_never(unreachable)
238
238
 
239
239
 
240
240
  def build_tool_meta(tool_def: SdkMcpTool[Any]) -> dict[str, Any] | None:
@@ -197,7 +197,7 @@ GrepInput = TypedDict(
197
197
  },
198
198
  )
199
199
  """Input for the Grep tool. Powerful search built on ripgrep with regex support."""
200
- GrepInput.__pydantic_config__ = ConfigDict(extra="allow") # type: ignore[attr-defined]
200
+ GrepInput.__pydantic_config__ = ConfigDict(extra="allow") # ty: ignore[missing-attribute]
201
201
 
202
202
 
203
203
  @_extra_allow
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from dataclasses import dataclass
6
- from typing import Literal
6
+ from typing import Literal, cast
7
7
 
8
8
  from anthropic.types.beta import (
9
9
  BetaBase64ImageSourceParam,
@@ -98,7 +98,9 @@ class UserDocumentPrompt:
98
98
  title=self.title,
99
99
  context=self.context,
100
100
  )
101
- return {k: v for k, v in block.items() if v is not None} # type: ignore[return-value]
101
+ return cast(
102
+ "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
103
+ )
102
104
 
103
105
 
104
106
  @dataclass
@@ -120,7 +122,9 @@ class UserDocumentURLPrompt:
120
122
  title=self.title,
121
123
  context=self.context,
122
124
  )
123
- return {k: v for k, v in block.items() if v is not None} # type: ignore[return-value]
125
+ return cast(
126
+ "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
127
+ )
124
128
 
125
129
 
126
130
  @dataclass
@@ -148,7 +152,9 @@ class UserPlainTextDocumentPrompt:
148
152
  title=self.title,
149
153
  context=self.context,
150
154
  )
151
- return {k: v for k, v in block.items() if v is not None} # type: ignore[return-value]
155
+ return cast(
156
+ "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
157
+ )
152
158
 
153
159
 
154
160
  @dataclass
@@ -170,7 +176,9 @@ class UserFilePrompt:
170
176
  title=self.title,
171
177
  context=self.context,
172
178
  )
173
- return {k: v for k, v in block.items() if v is not None} # type: ignore[return-value]
179
+ return cast(
180
+ "BetaRequestDocumentBlockParam", {k: v for k, v in block.items() if v is not None}
181
+ )
174
182
 
175
183
 
176
184
  UserPrompt = (
@@ -260,6 +260,8 @@ class InitSystemMessage(BaseSystemMessage):
260
260
  per_turn_effort_active: bool | None = None
261
261
  ultrathink_available: bool | None = None
262
262
  ultrathink_typed_raises: bool | None = None
263
+ served_by_anthropic: bool | None = None
264
+ """Whether requests are served by Anthropic directly (undocumented)."""
263
265
  startup_timing: dict[str, Any] | None = None
264
266
  """Startup timing diagnostics (undocumented, nested phase timings)."""
265
267
 
@@ -0,0 +1,84 @@
1
+ """SubprocessCLITransport.close() must not leak cancellation into the caller.
2
+
3
+ Regression test for 1.2.0: tearing down the stderr reader inside the shielded
4
+ close() scope cancelled the host task, surfacing as a stray CancelledError
5
+ after close() returned.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import stat
12
+ import sys
13
+ import textwrap
14
+ from typing import TYPE_CHECKING
15
+
16
+ import anyio
17
+
18
+ from clawd_code_sdk._internal.transport.subprocess_cli import (
19
+ _ACTIVE_CHILDREN,
20
+ SubprocessCLITransport,
21
+ )
22
+ from clawd_code_sdk.models import ClaudeAgentOptions
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ from pathlib import Path
27
+
28
+
29
+ def _fake_cli(tmp_path: Path) -> Path:
30
+ """A stand-in CLI: answers -v, writes to stderr, then waits for stdin EOF."""
31
+ script = tmp_path / "fake-claude"
32
+ script.write_text(
33
+ textwrap.dedent(
34
+ f"""\
35
+ #!{sys.executable}
36
+ import sys
37
+ if "-v" in sys.argv:
38
+ print("9.9.9 (Claude Code)")
39
+ sys.exit(0)
40
+ sys.stderr.write("starting up\\n")
41
+ sys.stderr.flush()
42
+ sys.stdin.read()
43
+ """
44
+ )
45
+ )
46
+ script.chmod(script.stat().st_mode | stat.S_IEXEC)
47
+ return script
48
+
49
+
50
+ async def test_close_does_not_cancel_caller(tmp_path: Path) -> None:
51
+ stderr_lines: list[str] = []
52
+ options = ClaudeAgentOptions(cli_path=_fake_cli(tmp_path), stderr=stderr_lines.append)
53
+ transport = SubprocessCLITransport(options=options)
54
+ await transport.connect()
55
+ process = transport._process
56
+ assert process is not None
57
+ assert process in _ACTIVE_CHILDREN
58
+ await anyio.sleep(0.2) # let the stderr reader pick up the line
59
+
60
+ await transport.close()
61
+
62
+ # A leaked cancellation would be delivered at the next checkpoint.
63
+ await asyncio.sleep(0)
64
+ await anyio.sleep(0.01)
65
+ assert asyncio.current_task() is not None
66
+ assert not asyncio.current_task().cancelling() # type: ignore[union-attr]
67
+ assert process.returncode is not None
68
+ assert process not in _ACTIVE_CHILDREN
69
+ assert stderr_lines == ["starting up"]
70
+
71
+
72
+ async def test_close_from_cancelled_scope_still_reaps_child(tmp_path: Path) -> None:
73
+ options = ClaudeAgentOptions(cli_path=_fake_cli(tmp_path))
74
+ transport = SubprocessCLITransport(options=options)
75
+ await transport.connect()
76
+ process = transport._process
77
+ assert process is not None
78
+
79
+ with anyio.CancelScope() as scope:
80
+ scope.cancel()
81
+ await transport.close()
82
+
83
+ assert process.returncode is not None
84
+ assert process not in _ACTIVE_CHILDREN
File without changes
File without changes