clawd-code-sdk 1.6.2__tar.gz → 1.6.4__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 (54) hide show
  1. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/PKG-INFO +1 -1
  2. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/pyproject.toml +5 -4
  3. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/pyproject.toml.orig +5 -4
  4. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/__init__.py +0 -2
  5. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_errors.py +0 -2
  6. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/mcp_compat.py +0 -2
  7. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/option_warnings.py +0 -2
  8. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/query.py +81 -19
  9. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/sdk_mcp_bridge.py +0 -2
  10. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/session_mutations.py +0 -2
  11. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/sessions.py +53 -49
  12. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/transport/__init__.py +0 -2
  13. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/transport/subprocess_cli.py +0 -2
  14. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/transport/subprocess_utils.py +0 -2
  15. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_version.py +0 -2
  16. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/anthropic_stream.py +0 -2
  17. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/client.py +4 -4
  18. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/instrumentation.py +0 -2
  19. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/mcp_utils.py +0 -2
  20. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/__init__.py +0 -1
  21. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/agents.py +0 -2
  22. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/anthropic_types.py +0 -2
  23. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/base.py +0 -2
  24. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/content_blocks.py +0 -2
  25. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/context_usage.py +0 -2
  26. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/control.py +0 -2
  27. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/hooks.py +0 -2
  28. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/input_types.py +7 -9
  29. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/mcp.py +0 -2
  30. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/messages.py +0 -2
  31. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/options.py +0 -2
  32. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/output_types.py +0 -2
  33. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/permissions.py +0 -2
  34. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/prompt_requests.py +0 -2
  35. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/prompts.py +0 -2
  36. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/server_info.py +0 -2
  37. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/session.py +0 -2
  38. clawd_code_sdk-1.6.4/src/clawd_code_sdk/models/settings.py +4302 -0
  39. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/system_messages.py +0 -2
  40. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/thinking.py +0 -2
  41. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/models/usage.py +0 -2
  42. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/session.py +28 -10
  43. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/storage/chain.py +0 -2
  44. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/storage/helpers.py +0 -2
  45. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/storage/models.py +1 -3
  46. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/storage/replay.py +0 -2
  47. clawd_code_sdk-1.6.2/src/clawd_code_sdk/models/settings.py +0 -2501
  48. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/LICENSE +0 -0
  49. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/README.md +0 -0
  50. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_bundled/.gitignore +0 -0
  51. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/_internal/__init__.py +0 -0
  52. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/py.typed +0 -0
  53. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/storage/ARCHITECTURE.md +0 -0
  54. {clawd_code_sdk-1.6.2 → clawd_code_sdk-1.6.4}/src/clawd_code_sdk/storage/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clawd-code-sdk
3
- Version: 1.6.2
3
+ Version: 1.6.4
4
4
  Summary: Python SDK for Claude Code
5
5
  Keywords: ai,anthropic,claude,sdk
6
6
  Author: Philipp Temminghoff
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "clawd-code-sdk"
3
- version = "1.6.2"
3
+ version = "1.6.4"
4
4
  description = "Python SDK for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14"
@@ -67,7 +67,7 @@ dev = [
67
67
  benchmark = ["pyinstrument"]
68
68
  docs = [
69
69
  "mkdocstrings[python]",
70
- "mknodes>=4.0.0",
70
+ "mknodes>=4.5.1",
71
71
  ]
72
72
  lint = [
73
73
  "ruff==0.17.6",
@@ -151,7 +151,6 @@ extend-exclude = [
151
151
  target-version = "py314"
152
152
 
153
153
  [tool.ruff.lint]
154
- future-annotations = true
155
154
  select = [
156
155
  "A",
157
156
  "ANN",
@@ -165,7 +164,6 @@ select = [
165
164
  "EM",
166
165
  "EXE",
167
166
  "F",
168
- "FA",
169
167
  "FLY",
170
168
  "G",
171
169
  "I",
@@ -264,6 +262,9 @@ runtime-evaluated-decorators = [
264
262
  "typer.Typer.command",
265
263
  ]
266
264
 
265
+ [tool.ruff.lint.flake8-tidy-imports.banned-api."__future__.annotations"]
266
+ msg = "Python 3.14+ evaluates annotations lazily (PEP 649); drop the import."
267
+
267
268
  [tool.ruff.lint.isort]
268
269
  lines-after-imports = 2
269
270
  force-sort-within-sections = true
@@ -2,7 +2,7 @@
2
2
 
3
3
  [project]
4
4
  name = "clawd-code-sdk"
5
- version = "1.6.2"
5
+ version = "1.6.4"
6
6
  description = "Python SDK for Claude Code"
7
7
  readme = "README.md"
8
8
  requires-python = ">=3.14"
@@ -66,7 +66,7 @@ dev = [
66
66
  benchmark = ["pyinstrument"]
67
67
  docs = [
68
68
  "mkdocstrings[python]",
69
- "mknodes>=4.0.0",
69
+ "mknodes>=4.5.1",
70
70
  # Only add below (Copier)
71
71
  ]
72
72
  lint = [
@@ -148,7 +148,6 @@ extend-exclude = ["docs", "examples"]
148
148
  target-version = "py314"
149
149
 
150
150
  [tool.ruff.lint]
151
- future-annotations = true
152
151
  select = [
153
152
  "A", # Flake8-builtins
154
153
  "ANN", # Flake8-Annotations (enforces complete annotations; ty does not)
@@ -168,7 +167,6 @@ select = [
168
167
  # "ERA", # Eradicate
169
168
  "EXE", # flake8-executable
170
169
  "F", # PyFlakes
171
- "FA", # flake8-future-annotations
172
170
  # "FBT", # flake8-boolean-trap
173
171
  # "FIX", # flake8-fixme
174
172
  "FLY", # flynt
@@ -278,6 +276,9 @@ runtime-evaluated-decorators = [
278
276
  "typer.Typer.command",
279
277
  ]
280
278
 
279
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
280
+ "__future__.annotations".msg = "Python 3.14+ evaluates annotations lazily (PEP 649); drop the import."
281
+
281
282
  [tool.ruff.lint.isort]
282
283
  lines-after-imports = 2
283
284
  # lines-between-types = 1
@@ -1,7 +1,5 @@
1
1
  """Claude SDK for Python."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from ._errors import (
6
4
  APIError,
7
5
  AuthenticationError,
@@ -1,7 +1,5 @@
1
1
  """Error types for Claude SDK."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from typing import TYPE_CHECKING, Any, Literal
6
4
 
7
5
 
@@ -19,8 +19,6 @@ genuinely differ live here:
19
19
  Nothing outside this module may branch on the mcp version.
20
20
  """
21
21
 
22
- from __future__ import annotations
23
-
24
22
  from typing import TYPE_CHECKING, Any
25
23
  import weakref
26
24
 
@@ -1,7 +1,5 @@
1
1
  """Advisory warnings about option combinations (upstream #1081)."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from typing import TYPE_CHECKING
6
4
  import warnings
7
5
 
@@ -1,12 +1,10 @@
1
1
  """Query class for handling bidirectional control protocol."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  import asyncio
4
+ from collections import deque
6
5
  from contextlib import suppress
7
6
  from dataclasses import replace
8
7
  import logging
9
- import math
10
8
  import os
11
9
  from typing import TYPE_CHECKING, Any, Self, assert_never, cast
12
10
 
@@ -47,7 +45,7 @@ from clawd_code_sdk.models.control import SDKControlRequestUserDialogRequest
47
45
 
48
46
 
49
47
  if TYPE_CHECKING:
50
- from collections.abc import AsyncGenerator, AsyncIterator
48
+ from collections.abc import AsyncGenerator, AsyncIterator, Callable
51
49
 
52
50
  from mcp.server import Server as McpServer
53
51
 
@@ -76,6 +74,68 @@ _warned_control_subtypes: set[str] = set()
76
74
  MANIFEST_CAPTURE_TIMEOUT = 10.0
77
75
  """Seconds an in-process MCP server gets to answer the handshake captured for the CLI."""
78
76
 
77
+ MAX_BUFFERED_MESSAGES = 1000
78
+ """Messages read ahead of the consumer before the reader stops reading (back-pressure)."""
79
+
80
+
81
+ class _MessageBuffer:
82
+ """Messages from the reader to the consumer, bounded for back-pressure.
83
+
84
+ At the bound, ``put`` waits for the consumer, so the CLI's output piles up in its
85
+ pipe and the CLI blocks on write instead of the SDK growing memory. Exception: while
86
+ one of our control requests awaits its response (``may_overflow``), the reader keeps
87
+ reading past the bound, since the response comes through the same stream and the
88
+ caller may well be the consumer. The excess is drained once the consumer goes on.
89
+ """
90
+
91
+ def __init__(self, bound: int, may_overflow: Callable[[], bool]) -> None:
92
+ self._items: deque[dict[str, Any]] = deque()
93
+ self._bound = bound
94
+ self._may_overflow = may_overflow
95
+ self._space = asyncio.Event()
96
+ self._data = asyncio.Event()
97
+ self._closed = False
98
+
99
+ def __len__(self) -> int:
100
+ return len(self._items)
101
+
102
+ async def put(self, message: dict[str, Any], *, force: bool = False) -> None:
103
+ """Append ``message``, waiting while the buffer is full (unless ``force``)."""
104
+ if self._closed:
105
+ return
106
+ while (
107
+ not force
108
+ and not self._closed
109
+ and len(self._items) >= self._bound
110
+ and not self._may_overflow()
111
+ ):
112
+ self._space.clear()
113
+ await self._space.wait()
114
+ self._items.append(message)
115
+ self._data.set()
116
+
117
+ async def get(self) -> dict[str, Any] | None:
118
+ """Next message, or None once the buffer is closed."""
119
+ while not self._items:
120
+ if self._closed:
121
+ return None
122
+ self._data.clear()
123
+ await self._data.wait()
124
+ message = self._items.popleft()
125
+ self._space.set()
126
+ return message
127
+
128
+ def wake(self) -> None:
129
+ """Re-check the bound (a control request started: the reader may overflow)."""
130
+ self._space.set()
131
+
132
+ def close(self) -> None:
133
+ """Drop what's buffered; ``get`` returns None from now on."""
134
+ self._closed = True
135
+ self._items.clear()
136
+ self._space.set()
137
+ self._data.set()
138
+
79
139
 
80
140
  async def _handshake(name: str, bridge: SdkMcpBridge) -> SdkMcpServerManifest | None:
81
141
  """``name``'s handshake results (initialize, first tools/list), or None if it errs."""
@@ -130,6 +190,7 @@ class Query:
130
190
  on_elicitation: OnElicitation | None = None,
131
191
  hooks: dict[HookEvent, list[HookMatcher]] | None = None,
132
192
  sdk_mcp_servers: dict[str, McpServer] | None = None,
193
+ max_buffered_messages: int = MAX_BUFFERED_MESSAGES,
133
194
  ) -> None:
134
195
  """Initialize Query with transport and callbacks.
135
196
 
@@ -140,6 +201,8 @@ class Query:
140
201
  on_elicitation: Optional callback for MCP elicitation requests
141
202
  hooks: Optional hook configurations
142
203
  sdk_mcp_servers: Optional SDK MCP server instances
204
+ max_buffered_messages: Messages read ahead of a slow consumer before the
205
+ reader waits for it (see `_MessageBuffer`)
143
206
  """
144
207
  self.transport = transport
145
208
  self.can_use_tool = can_use_tool
@@ -160,10 +223,10 @@ class Query:
160
223
  self.hook_callbacks: dict[str, HookCallback] = {}
161
224
  self.next_callback_id = 0
162
225
  self._request_counter = 0
163
- # Message stream
164
- self._message_send, self._message_receive = anyio.create_memory_object_stream[
165
- dict[str, Any]
166
- ](max_buffer_size=math.inf)
226
+ # Message stream (bounded; control responses are routed by the reader itself)
227
+ self._messages = _MessageBuffer(
228
+ max_buffered_messages, may_overflow=lambda: bool(self.pending_control_responses)
229
+ )
167
230
  self._read_task: asyncio.Task[None] | None = None
168
231
  self._child_tasks: set[asyncio.Task[Any]] = set()
169
232
  self._inflight_requests: dict[str, asyncio.Task[Any]] = {}
@@ -325,14 +388,14 @@ class Query:
325
388
  case {"type": "result"}:
326
389
  self._first_result_event.set()
327
390
  self._last_error_result = message if message.get("is_error") else None
328
- await self._message_send.send(message)
391
+ await self._messages.put(message)
329
392
  case {"type": "system", "subtype": "session_state_changed"}:
330
- await self._message_send.send(message)
393
+ await self._messages.put(message)
331
394
  case _: # Regular SDK messages go to the stream
332
395
  # The conversation moved on: a ProcessError now is a fresh
333
396
  # crash, not the exit that follows an error result.
334
397
  self._last_error_result = None
335
- await self._message_send.send(message)
398
+ await self._messages.put(message)
336
399
 
337
400
  except anyio.get_cancelled_exc_class():
338
401
  # Task was cancelled - this is expected behavior
@@ -359,12 +422,12 @@ class Query:
359
422
  self._fail_control_requests(pending_error)
360
423
  # Put the typed error in the stream so iterators re-raise it as-is
361
424
  error_msg = {"type": "error", "error": str(pending_error), "exception": pending_error}
362
- await self._message_send.send(error_msg)
425
+ await self._messages.put(error_msg, force=True)
363
426
  finally:
364
427
  # Also after a clean end of stdout: nothing will answer anymore.
365
428
  self._fail_control_requests(CLIConnectionError("Claude Code CLI output ended"))
366
429
  # Always signal end of stream
367
- await self._message_send.send({"type": "end"})
430
+ await self._messages.put({"type": "end"}, force=True)
368
431
 
369
432
  def _fail_control_requests(self, error: Exception) -> None:
370
433
  """Fail pending and later control requests fast instead of letting them time out."""
@@ -430,7 +493,8 @@ class Query:
430
493
  await self.write_json(SDKControlResponse(type="control_response", response=response))
431
494
  if strict_messages():
432
495
  exc = MessageParseError(f"Invalid control request {subtype!r}: {error}", request)
433
- await self._message_send.send({"type": "error", "error": str(exc), "exception": exc})
496
+ error_msg = {"type": "error", "error": str(exc), "exception": exc}
497
+ await self._messages.put(error_msg, force=True)
434
498
  elif str(subtype) not in _warned_control_subtypes:
435
499
  _warned_control_subtypes.add(str(subtype))
436
500
  logger.warning("Answered an unsupported control request %r: %s", subtype, error)
@@ -499,6 +563,7 @@ class Query:
499
563
  # Create event for response
500
564
  event = anyio.Event()
501
565
  self.pending_control_responses[request_id] = event
566
+ self._messages.wake() # A reader waiting at the bound must read on to the response
502
567
  # Build and send request
503
568
  control_request = {
504
569
  "type": "control_request",
@@ -564,7 +629,7 @@ class Query:
564
629
 
565
630
  async def receive_messages(self) -> AsyncGenerator[dict[str, Any]]:
566
631
  """Receive SDK messages (not control messages)."""
567
- async for message in self._message_receive:
632
+ while (message := await self._messages.get()) is not None:
568
633
  # Check for special messages
569
634
  match message.get("type"):
570
635
  case "end":
@@ -598,10 +663,7 @@ class Query:
598
663
  self.hook_callbacks.clear()
599
664
  self.pending_control_responses.clear()
600
665
  self.pending_control_results.clear()
601
- with suppress(Exception):
602
- await self._message_send.aclose()
603
- with suppress(Exception):
604
- await self._message_receive.aclose()
666
+ self._messages.close()
605
667
 
606
668
  # Make Query an async context manager
607
669
  async def __aenter__(self) -> Self:
@@ -25,8 +25,6 @@ dropped, and server-to-client requests (roots, sampling, elicitation) are
25
25
  refused with "method not found".
26
26
  """
27
27
 
28
- from __future__ import annotations
29
-
30
28
  import asyncio
31
29
  from contextlib import suppress
32
30
  import logging
@@ -16,8 +16,6 @@ tail scan window, the CLI absorbs it into its cache and re-appends the SDK
16
16
  value — not the stale CLI value.
17
17
  """
18
18
 
19
- from __future__ import annotations
20
-
21
19
  from dataclasses import dataclass
22
20
  from datetime import UTC, datetime
23
21
  import errno
@@ -1,11 +1,9 @@
1
1
  """Session listing implementation.
2
2
 
3
- Scans ~/.claude/projects/<sanitized-cwd>/ for .jsonl session files and
3
+ Scans `~/.claude/projects/<sanitized-cwd>/` for .jsonl session files and
4
4
  extracts metadata from stat + head/tail reads without full JSONL parsing.
5
5
  """
6
6
 
7
- from __future__ import annotations
8
-
9
7
  from dataclasses import dataclass
10
8
  from datetime import datetime
11
9
  import os
@@ -487,21 +485,26 @@ def _parse_session_info_from_lite(
487
485
  # ---------------------------------------------------------------------------
488
486
 
489
487
 
490
- def _read_sessions_from_dir(
491
- project_dir: Path, project_path: str | None = None
492
- ) -> list[SDKSessionInfo]:
493
- """Reads session files from a single project directory.
488
+ @dataclass(frozen=True)
489
+ class _SessionCandidate:
490
+ """A transcript found by a directory scan: stat-ed, not read yet."""
494
491
 
495
- Each file gets a stat + head/tail read. Filters out sidechain sessions
496
- and metadata-only sessions (no title/summary/prompt).
497
- """
492
+ path: Path
493
+ session_id: str
494
+ project_path: str | None
495
+ mtime: int
496
+ """Milliseconds, like ``SDKSessionInfo.last_modified`` (which is the file's mtime)."""
497
+
498
+
499
+ def _session_candidates(
500
+ project_dir: Path, project_path: str | None = None
501
+ ) -> list[_SessionCandidate]:
502
+ """The session files of one project directory, with their mtimes (one stat each)."""
498
503
  try:
499
- entries = list(project_dir.iterdir())
504
+ entries = list(os.scandir(project_dir))
500
505
  except OSError:
501
506
  return []
502
-
503
- results: list[SDKSessionInfo] = []
504
-
507
+ candidates: list[_SessionCandidate] = []
505
508
  for entry in entries:
506
509
  name = entry.name
507
510
  if not name.endswith(".jsonl"):
@@ -509,28 +512,38 @@ def _read_sessions_from_dir(
509
512
  session_id = _validate_uuid(name[:-6])
510
513
  if not session_id:
511
514
  continue
512
-
513
- lite = _read_session_lite(entry)
514
- if lite is None:
515
+ try:
516
+ mtime = int(entry.stat().st_mtime * 1000)
517
+ except OSError:
515
518
  continue
519
+ candidates.append(_SessionCandidate(Path(entry.path), session_id, project_path, mtime))
520
+ return candidates
516
521
 
517
- info = _parse_session_info_from_lite(session_id, lite, project_path)
518
- if info is not None:
519
- results.append(info)
520
522
 
521
- return results
522
-
523
-
524
- def _deduplicate_by_session_id(
525
- sessions: list[SDKSessionInfo],
523
+ def _read_newest_sessions(
524
+ candidates: list[_SessionCandidate], limit: int | None, offset: int
526
525
  ) -> list[SDKSessionInfo]:
527
- """Deduplicates by session_id, keeping the newest last_modified."""
526
+ """Reads candidates newest first until the page is full, then sorts and pages.
527
+
528
+ Sidechain and metadata-only sessions are skipped; a session found in several
529
+ directories counts once, with its newest readable copy.
530
+ """
531
+ candidates = sorted(candidates, key=lambda c: c.mtime, reverse=True)
532
+ wanted = offset + limit if limit is not None and limit > 0 else None
528
533
  by_id: dict[str, SDKSessionInfo] = {}
529
- for s in sessions:
530
- existing = by_id.get(s.session_id)
531
- if existing is None or s.last_modified > existing.last_modified:
532
- by_id[s.session_id] = s
533
- return list(by_id.values())
534
+ for candidate in candidates:
535
+ if candidate.session_id in by_id:
536
+ continue
537
+ lite = _read_session_lite(candidate.path)
538
+ if lite is None:
539
+ continue
540
+ info = _parse_session_info_from_lite(candidate.session_id, lite, candidate.project_path)
541
+ if info is None:
542
+ continue
543
+ by_id[candidate.session_id] = info
544
+ if wanted is not None and len(by_id) >= wanted:
545
+ break
546
+ return _apply_sort_limit_offset(list(by_id.values()), limit, offset)
534
547
 
535
548
 
536
549
  def _apply_sort_limit_offset(
@@ -562,8 +575,7 @@ def _list_sessions_for_project(
562
575
  project_dir = _find_project_dir(canonical_dir)
563
576
  if project_dir is None:
564
577
  return []
565
- sessions = _read_sessions_from_dir(project_dir, canonical_dir)
566
- return _apply_sort_limit_offset(sessions, limit, offset)
578
+ return _read_newest_sessions(_session_candidates(project_dir, canonical_dir), limit, offset)
567
579
 
568
580
  # Worktree-aware scanning: find all project dirs matching any worktree
569
581
  projects_dir = _get_projects_dir()
@@ -582,11 +594,10 @@ def _list_sessions_for_project(
582
594
  # Fall back to single project dir
583
595
  project_dir = _find_project_dir(canonical_dir)
584
596
  if project_dir is None:
585
- return _apply_sort_limit_offset([], limit, offset)
586
- sessions = _read_sessions_from_dir(project_dir, canonical_dir)
587
- return _apply_sort_limit_offset(sessions, limit, offset)
597
+ return []
598
+ return _read_newest_sessions(_session_candidates(project_dir, canonical_dir), limit, offset)
588
599
 
589
- all_sessions: list[SDKSessionInfo] = []
600
+ candidates: list[_SessionCandidate] = []
590
601
  seen_dirs: set[str] = set()
591
602
 
592
603
  # Always include the user's actual directory (handles subdirectories
@@ -595,8 +606,7 @@ def _list_sessions_for_project(
595
606
  if canonical_project_dir is not None:
596
607
  dir_base = canonical_project_dir.name
597
608
  seen_dirs.add(dir_base.lower() if case_insensitive else dir_base)
598
- sessions = _read_sessions_from_dir(canonical_project_dir, canonical_dir)
599
- all_sessions.extend(sessions)
609
+ candidates.extend(_session_candidates(canonical_project_dir, canonical_dir))
600
610
 
601
611
  for entry in all_dirents:
602
612
  dir_name = entry.name.lower() if case_insensitive else entry.name
@@ -612,12 +622,10 @@ def _list_sessions_for_project(
612
622
  )
613
623
  if is_match:
614
624
  seen_dirs.add(dir_name)
615
- sessions = _read_sessions_from_dir(entry, wt_path)
616
- all_sessions.extend(sessions)
625
+ candidates.extend(_session_candidates(entry, wt_path))
617
626
  break
618
627
 
619
- deduped = _deduplicate_by_session_id(all_sessions)
620
- return _apply_sort_limit_offset(deduped, limit, offset)
628
+ return _read_newest_sessions(candidates, limit, offset)
621
629
 
622
630
 
623
631
  def _list_all_sessions(limit: int | None, offset: int) -> list[SDKSessionInfo]:
@@ -629,12 +637,8 @@ def _list_all_sessions(limit: int | None, offset: int) -> list[SDKSessionInfo]:
629
637
  except OSError:
630
638
  return []
631
639
 
632
- all_sessions: list[SDKSessionInfo] = []
633
- for project_dir in project_dirs:
634
- all_sessions.extend(_read_sessions_from_dir(project_dir))
635
-
636
- deduped = _deduplicate_by_session_id(all_sessions)
637
- return _apply_sort_limit_offset(deduped, limit, offset)
640
+ candidates = [c for project_dir in project_dirs for c in _session_candidates(project_dir)]
641
+ return _read_newest_sessions(candidates, limit, offset)
638
642
 
639
643
 
640
644
  def list_sessions(
@@ -1,7 +1,5 @@
1
1
  """Transport implementations for Claude SDK."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from abc import ABC, abstractmethod
6
4
  from typing import TYPE_CHECKING, Any
7
5
 
@@ -1,7 +1,5 @@
1
1
  """Subprocess transport implementation using Claude Code CLI."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  import asyncio
6
4
  import atexit
7
5
  from collections import deque
@@ -1,7 +1,5 @@
1
1
  """Subprocess transport implementation using Claude Code CLI."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  import functools
6
4
  import logging
7
5
  import os
@@ -1,7 +1,5 @@
1
1
  """Version information for clawd-code-sdk."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from importlib.metadata import version
6
4
 
7
5
 
@@ -10,8 +10,6 @@ replays, reconnection) are synthesized into the full event sequence
10
10
  (message_start → content_block_start → delta → stop → message_delta → message_stop).
11
11
  """
12
12
 
13
- from __future__ import annotations
14
-
15
13
  import json
16
14
  from typing import TYPE_CHECKING, assert_never
17
15
 
@@ -1,7 +1,5 @@
1
1
  """Claude SDK Client for interacting with Claude Code."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  import asyncio
6
4
  import contextlib
7
5
  import logging
@@ -11,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Literal, Self, cast, get_args
11
9
  from uuid import uuid4
12
10
 
13
11
  import anyenv
12
+ import anyio
14
13
  from pydantic import ValidationError
15
14
 
16
15
  from clawd_code_sdk._errors import CLIConnectionError, MessageParseError
@@ -231,8 +230,9 @@ class ClaudeSDKClient:
231
230
  except BaseException:
232
231
  # `async with` never reaches __aexit__ when connect() fails: don't leak the
233
232
  # CLI process and the reader task.
234
- with contextlib.suppress(Exception): # the connect error is the one to see
235
- await asyncio.shield(self.disconnect())
233
+ # Shielded: an anyio scope that cancelled connect() stays cancelled.
234
+ with anyio.CancelScope(shield=True), contextlib.suppress(Exception):
235
+ await self.disconnect() # the connect error is the one to see
236
236
  self._query = None
237
237
  raise
238
238
 
@@ -1,5 +1,3 @@
1
- from __future__ import annotations
2
-
3
1
  from typing import TYPE_CHECKING, Any
4
2
 
5
3
  from logfire._internal.integrations.llm_providers.semconv import (
@@ -5,8 +5,6 @@ them to the CLI through mcp's own in-memory transport (see
5
5
  ``clawd_code_sdk._internal.sdk_mcp_bridge``), which works on mcp 1.x and 2.x.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  from dataclasses import dataclass
11
9
  import logging
12
10
  from typing import TYPE_CHECKING, Any, assert_never
@@ -1,6 +1,5 @@
1
1
  """Type definitions for Claude SDK."""
2
2
 
3
- from __future__ import annotations
4
3
  from collections.abc import Callable
5
4
 
6
5
  from mcp.types import ElicitResult
@@ -1,7 +1,5 @@
1
1
  """Agent definitions and preset configurations."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from collections.abc import Mapping, Sequence
6
4
  from typing import Any, Literal, TypedDict
7
5
 
@@ -5,8 +5,6 @@ that can appear in tool results from the Anthropic SDK. These types are
5
5
  used to provide proper typing for ToolResultBlock.content.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  import functools
11
9
  from typing import Annotated
12
10
 
@@ -1,7 +1,5 @@
1
1
  """Base type aliases, literals, and thinking configuration types."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  import sys
6
4
  from typing import Literal
7
5
 
@@ -5,8 +5,6 @@ messages) and in persisted JSONL session transcripts. A single set of models
5
5
  therefore serves both purposes, avoiding a redundant conversion layer.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  from collections.abc import Sequence
11
9
  from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeIs, assert_never, cast, get_args
12
10
 
@@ -1,7 +1,5 @@
1
1
  """Context window usage breakdown models."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from typing import Literal
6
4
 
7
5
  from pydantic import ConfigDict, Field