clawd-code-sdk 1.1.3__tar.gz → 1.1.5__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 (85) hide show
  1. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/PKG-INFO +1 -1
  2. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/pyproject.toml +1 -1
  3. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_internal/query.py +5 -1
  4. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_internal/session_mutations.py +2 -11
  5. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_internal/sessions.py +34 -157
  6. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_internal/transport/subprocess_cli.py +2 -6
  7. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/client.py +13 -0
  8. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/__init__.py +10 -0
  9. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/content_blocks.py +5 -3
  10. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/control.py +2 -0
  11. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/messages.py +16 -3
  12. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/usage.py +7 -2
  13. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/.gitignore +0 -0
  14. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/LICENSE +0 -0
  15. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/README.md +0 -0
  16. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/__init__.py +0 -0
  17. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_bundled/.gitignore +0 -0
  18. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_errors.py +0 -0
  19. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_internal/__init__.py +0 -0
  20. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_internal/transport/__init__.py +0 -0
  21. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_internal/transport/subprocess_utils.py +0 -0
  22. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/_version.py +0 -0
  23. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/anthropic_stream.py +0 -0
  24. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/instrumentation.py +0 -0
  25. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/list_sessions.py +0 -0
  26. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/mcp_utils.py +0 -0
  27. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/agents.py +0 -0
  28. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/anthropic_types.py +0 -0
  29. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/base.py +0 -0
  30. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/context_usage.py +0 -0
  31. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/hooks.py +0 -0
  32. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/input_types.py +0 -0
  33. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/mcp.py +0 -0
  34. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/options.py +0 -0
  35. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/output_types.py +0 -0
  36. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/permissions.py +0 -0
  37. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/prompt_requests.py +0 -0
  38. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/prompts.py +0 -0
  39. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/server_info.py +0 -0
  40. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/session.py +0 -0
  41. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/settings.py +0 -0
  42. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/system_messages.py +0 -0
  43. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/models/thinking.py +0 -0
  44. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/py.typed +0 -0
  45. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/session.py +0 -0
  46. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/storage/ARCHITECTURE.md +0 -0
  47. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/storage/__init__.py +0 -0
  48. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/storage/helpers.py +0 -0
  49. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/storage/models.py +0 -0
  50. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/storage/replay.py +0 -0
  51. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/src/clawd_code_sdk/usage.py +0 -0
  52. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/__init__.py +0 -0
  53. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/conftest.py +0 -0
  54. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/__init__.py +0 -0
  55. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_agents_and_settings.py +0 -0
  56. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_dynamic_control.py +0 -0
  57. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_hook_events.py +0 -0
  58. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_hooks.py +0 -0
  59. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_include_partial_messages.py +0 -0
  60. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_mcp_resources.py +0 -0
  61. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_mcp_tools.py +0 -0
  62. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_sdk_mcp_resources.py +0 -0
  63. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_sdk_mcp_tools.py +0 -0
  64. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_slash_commands.py +0 -0
  65. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_stderr_callback.py +0 -0
  66. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_storage_parsing.py +0 -0
  67. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_structured_output.py +0 -0
  68. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_subagent_invocation.py +0 -0
  69. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/e2e/test_tool_permissions.py +0 -0
  70. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/mcp_server.py +0 -0
  71. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/mock_claude_server.py +0 -0
  72. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_changelog.py +0 -0
  73. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_client.py +0 -0
  74. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_errors.py +0 -0
  75. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_image.png +0 -0
  76. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_integration.py +0 -0
  77. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_message_parser.py +0 -0
  78. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_sdk_mcp_integration.py +0 -0
  79. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_session.py +0 -0
  80. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_session_mutations.py +0 -0
  81. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_sessions.py +0 -0
  82. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_streaming_client.py +0 -0
  83. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_subprocess_buffering.py +0 -0
  84. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/tests/test_tool_callbacks.py +0 -0
  85. {clawd_code_sdk-1.1.3 → clawd_code_sdk-1.1.5}/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.1.3
3
+ Version: 1.1.5
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.1.3"
3
+ version = "1.1.5"
4
4
  description = "Python SDK for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -54,6 +54,7 @@ if TYPE_CHECKING:
54
54
  OutgoingControlRequest,
55
55
  PermissionResult,
56
56
  RequestId,
57
+ SDKControlRequest,
57
58
  )
58
59
 
59
60
  logger = logging.getLogger(__name__)
@@ -461,6 +462,9 @@ class Query:
461
462
  return message
462
463
  raise StopAsyncIteration
463
464
 
464
- async def write_json(self, data: Any) -> None:
465
+ async def write_json(
466
+ self,
467
+ data: SDKControlResponse | SDKControlRequest | dict[str, Any],
468
+ ) -> None:
465
469
  """Write a JSON-serializable object to the transport."""
466
470
  await self.transport.write(anyenv.dump_json(data) + "\n")
@@ -470,11 +470,7 @@ def _find_session_file_with_dir(
470
470
  if result:
471
471
  return result
472
472
 
473
- try:
474
- worktree_paths = _get_worktree_paths(canonical)
475
- except Exception:
476
- worktree_paths = []
477
- for wt in worktree_paths:
473
+ for wt in _get_worktree_paths(canonical):
478
474
  if wt == canonical:
479
475
  continue
480
476
  wt_project_dir = _find_project_dir(wt)
@@ -548,7 +544,6 @@ def _append_to_session(session_id: str, data: str, directory: str | None) -> Non
548
544
 
549
545
  if directory:
550
546
  canonical = _canonicalize_path(directory)
551
-
552
547
  # Try the exact/prefix-matched project directory first.
553
548
  project_dir = _find_project_dir(canonical)
554
549
  if project_dir is not None and _try_append(project_dir / file_name, data):
@@ -556,11 +551,7 @@ def _append_to_session(session_id: str, data: str, directory: str | None) -> Non
556
551
 
557
552
  # Worktree fallback — matches list_sessions/get_session_messages.
558
553
  # Sessions may live under a different worktree root.
559
- try:
560
- worktree_paths = _get_worktree_paths(canonical)
561
- except Exception:
562
- worktree_paths = []
563
- for wt in worktree_paths:
554
+ for wt in _get_worktree_paths(canonical):
564
555
  if wt == canonical:
565
556
  continue # already tried above
566
557
  wt_project_dir = _find_project_dir(wt)
@@ -6,13 +6,14 @@ extracts metadata from stat + head/tail reads without full JSONL parsing.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ from dataclasses import dataclass
9
10
  from datetime import datetime
10
11
  import os
11
12
  from pathlib import Path
12
13
  import re
13
14
  import subprocess
14
15
  import sys
15
- from typing import Any, Literal
16
+ from typing import Any
16
17
  import unicodedata
17
18
 
18
19
  import anyenv
@@ -26,7 +27,6 @@ from clawd_code_sdk.models.session import SDKSessionInfo, SessionMessage
26
27
 
27
28
  # Size of the head/tail buffer for lite metadata reads.
28
29
  LITE_READ_BUF_SIZE = 65536
29
-
30
30
  # Maximum length for a single filesystem path component. Most filesystems
31
31
  # limit individual components to 255 bytes. We use 200 to leave room for
32
32
  # the hash suffix and separator.
@@ -50,6 +50,7 @@ _COMMAND_NAME_RE = re.compile(r"<command-name>(.*?)</command-name>")
50
50
 
51
51
  _SANITIZE_RE = re.compile(r"[^a-zA-Z0-9]")
52
52
 
53
+ case_insensitive = sys.platform == "win32"
53
54
 
54
55
  # ---------------------------------------------------------------------------
55
56
  # UUID validation
@@ -314,16 +315,14 @@ def _extract_first_prompt_from_head(head: str) -> str:
314
315
  # ---------------------------------------------------------------------------
315
316
 
316
317
 
318
+ @dataclass(kw_only=True, slots=True)
317
319
  class _LiteSessionFile:
318
320
  """Result of reading a session file's head, tail, mtime and size."""
319
321
 
320
- __slots__ = ("head", "mtime", "size", "tail")
321
-
322
- def __init__(self, mtime: int, size: int, head: str, tail: str) -> None:
323
- self.mtime = mtime
324
- self.size = size
325
- self.head = head
326
- self.tail = tail
322
+ mtime: int
323
+ size: int
324
+ head: str
325
+ tail: str
327
326
 
328
327
 
329
328
  def _read_session_lite(file_path: Path) -> _LiteSessionFile | None:
@@ -381,12 +380,11 @@ def _get_worktree_paths(cwd: str) -> list[str]:
381
380
  if result.returncode != 0 or not result.stdout:
382
381
  return []
383
382
 
384
- paths = []
385
- for line in result.stdout.split("\n"):
386
- if line.startswith("worktree "):
387
- path = unicodedata.normalize("NFC", line[len("worktree ") :])
388
- paths.append(path)
389
- return paths
383
+ return [
384
+ unicodedata.normalize("NFC", i[len("worktree ") :])
385
+ for i in result.stdout.split("\n")
386
+ if i.startswith("worktree ")
387
+ ]
390
388
 
391
389
 
392
390
  # ---------------------------------------------------------------------------
@@ -554,15 +552,7 @@ def _list_sessions_for_project(
554
552
  ) -> list[SDKSessionInfo]:
555
553
  """Lists sessions for a specific project directory (and its worktrees)."""
556
554
  canonical_dir = _canonicalize_path(directory)
557
-
558
- if include_worktrees:
559
- try:
560
- worktree_paths = _get_worktree_paths(canonical_dir)
561
- except Exception:
562
- worktree_paths = []
563
- else:
564
- worktree_paths = []
565
-
555
+ worktree_paths = _get_worktree_paths(canonical_dir) if include_worktrees else []
566
556
  # No worktrees (or git not available / scanning disabled) —
567
557
  # just scan the single project dir
568
558
  if len(worktree_paths) <= 1:
@@ -574,8 +564,6 @@ def _list_sessions_for_project(
574
564
 
575
565
  # Worktree-aware scanning: find all project dirs matching any worktree
576
566
  projects_dir = _get_projects_dir()
577
- case_insensitive = sys.platform == "win32"
578
-
579
567
  # Sort worktree paths by sanitized prefix length (longest first) so
580
568
  # more specific matches take priority over shorter ones
581
569
  indexed = []
@@ -673,23 +661,6 @@ def list_sessions(
673
661
 
674
662
  Returns:
675
663
  List of ``SDKSessionInfo`` sorted by ``last_modified`` descending.
676
-
677
- Example:
678
- List sessions for a specific project::
679
-
680
- sessions = list_sessions(directory="/path/to/project")
681
-
682
- Paginate::
683
-
684
- page1 = list_sessions(limit=50)
685
- page2 = list_sessions(limit=50, offset=50)
686
-
687
- List sessions without scanning git worktrees::
688
-
689
- sessions = list_sessions(
690
- directory="/path/to/project",
691
- include_worktrees=False,
692
- )
693
664
  """
694
665
  if directory:
695
666
  return _list_sessions_for_project(directory, limit, offset, include_worktrees)
@@ -701,10 +672,7 @@ def list_sessions(
701
672
  # ---------------------------------------------------------------------------
702
673
 
703
674
 
704
- def get_session_info(
705
- session_id: str,
706
- directory: str | None = None,
707
- ) -> SDKSessionInfo | None:
675
+ def get_session_info(session_id: str, directory: str | None = None) -> SDKSessionInfo | None:
708
676
  """Reads metadata for a single session by ID.
709
677
 
710
678
  Wraps ``_read_session_lite`` for one file — no O(n) directory scan.
@@ -721,20 +689,6 @@ def get_session_info(
721
689
  Returns:
722
690
  ``SDKSessionInfo`` for the session, or ``None`` if the session file
723
691
  is not found, is a sidechain session, or has no extractable summary.
724
-
725
- Example:
726
- Look up a session in a specific project::
727
-
728
- info = get_session_info(
729
- "550e8400-e29b-41d4-a716-446655440000",
730
- directory="/path/to/project",
731
- )
732
- if info:
733
- print(info.summary)
734
-
735
- Search all projects for a session::
736
-
737
- info = get_session_info("550e8400-e29b-41d4-a716-446655440000")
738
692
  """
739
693
  uuid = _validate_uuid(session_id)
740
694
  if not uuid:
@@ -744,25 +698,16 @@ def get_session_info(
744
698
  if directory:
745
699
  canonical = _canonicalize_path(directory)
746
700
  project_dir = _find_project_dir(canonical)
747
- if project_dir is not None:
748
- lite = _read_session_lite(project_dir / file_name)
749
- if lite is not None:
750
- return _parse_session_info_from_lite(uuid, lite, canonical)
751
-
701
+ if project_dir and (lite := _read_session_lite(project_dir / file_name)):
702
+ return _parse_session_info_from_lite(uuid, lite, canonical)
752
703
  # Worktree fallback — matches get_session_messages semantics.
753
704
  # Sessions may live under a different worktree root.
754
- try:
755
- worktree_paths = _get_worktree_paths(canonical)
756
- except Exception:
757
- worktree_paths = []
758
- for wt in worktree_paths:
705
+ for wt in _get_worktree_paths(canonical):
759
706
  if wt == canonical:
760
707
  continue
761
708
  wt_project_dir = _find_project_dir(wt)
762
- if wt_project_dir is not None:
763
- lite = _read_session_lite(wt_project_dir / file_name)
764
- if lite is not None:
765
- return _parse_session_info_from_lite(uuid, lite, wt)
709
+ if wt_project_dir and (lite := _read_session_lite(wt_project_dir / file_name)):
710
+ return _parse_session_info_from_lite(uuid, lite, wt)
766
711
 
767
712
  return None
768
713
 
@@ -813,31 +758,19 @@ def _read_session_file(session_id: str, directory: str | None) -> str | None:
813
758
 
814
759
  if directory:
815
760
  canonical_dir = _canonicalize_path(directory)
816
-
817
761
  # Try the exact/prefix-matched project directory first
818
762
  project_dir = _find_project_dir(canonical_dir)
819
- if project_dir is not None:
820
- content = _try_read_session_file(project_dir, file_name)
821
- if content:
822
- return content
823
-
763
+ if project_dir and (content := _try_read_session_file(project_dir, file_name)):
764
+ return content
824
765
  # Try worktree paths — sessions may live under a different worktree root
825
- try:
826
- worktree_paths = _get_worktree_paths(canonical_dir)
827
- except Exception:
828
- worktree_paths = []
829
-
830
- for wt in worktree_paths:
766
+ for wt in _get_worktree_paths(canonical_dir):
831
767
  if wt == canonical_dir:
832
768
  continue # already tried above
833
769
  wt_project_dir = _find_project_dir(wt)
834
- if wt_project_dir is not None:
835
- content = _try_read_session_file(wt_project_dir, file_name)
836
- if content:
837
- return content
770
+ if wt_project_dir and (content := _try_read_session_file(wt_project_dir, file_name)):
771
+ return content
838
772
 
839
773
  return None
840
-
841
774
  # No directory provided — search all project directories
842
775
  projects_dir = _get_projects_dir()
843
776
  try:
@@ -846,8 +779,7 @@ def _read_session_file(session_id: str, directory: str | None) -> str | None:
846
779
  return None
847
780
 
848
781
  for entry in dirents:
849
- content = _try_read_session_file(entry, file_name)
850
- if content:
782
+ if content := (_try_read_session_file(entry, file_name)):
851
783
  return content
852
784
 
853
785
  return None
@@ -874,12 +806,9 @@ def _parse_transcript_entries(content: str) -> list[_TranscriptEntry]:
874
806
  continue
875
807
 
876
808
  try:
877
- entry = anyenv.load_json(line)
809
+ entry = anyenv.load_json(line, return_type=dict)
878
810
  except (anyenv.JsonLoadError, ValueError):
879
811
  continue
880
-
881
- if not isinstance(entry, dict):
882
- continue
883
812
  entry_type = entry.get("type")
884
813
  if entry_type in _TRANSCRIPT_ENTRY_TYPES and isinstance(entry.get("uuid"), str):
885
814
  entries.append(entry)
@@ -901,26 +830,12 @@ def _build_conversation_chain(
901
830
  """
902
831
  if not entries:
903
832
  return []
904
-
905
- # Index by uuid for O(1) parent lookup
906
- by_uuid: dict[str, _TranscriptEntry] = {}
907
- for entry in entries:
908
- by_uuid[entry["uuid"]] = entry
909
-
833
+ by_uuid = {e["uuid"]: e for e in entries}
910
834
  # Build index of entry positions (file order) for tie-breaking
911
- entry_index: dict[str, int] = {}
912
- for i, entry in enumerate(entries):
913
- entry_index[entry["uuid"]] = i
914
-
835
+ entry_index = {e["uuid"]: i for i, e in enumerate(entries)}
915
836
  # Find terminal messages (no children point to them via parentUuid)
916
- parent_uuids: set[str] = set()
917
- for entry in entries:
918
- parent = entry.get("parentUuid")
919
- if parent:
920
- parent_uuids.add(parent)
921
-
837
+ parent_uuids = {parent for e in entries if (parent := e.get("parentUuid"))}
922
838
  terminals = [e for e in entries if e["uuid"] not in parent_uuids]
923
-
924
839
  # From each terminal, walk back to find the nearest user/assistant leaf
925
840
  leaves: list[_TranscriptEntry] = []
926
841
  for terminal in terminals:
@@ -995,12 +910,10 @@ def _is_visible_message(entry: _TranscriptEntry) -> bool:
995
910
 
996
911
  def _to_session_message(entry: _TranscriptEntry) -> SessionMessage:
997
912
  """Converts a transcript entry dict into a SessionMessage."""
998
- entry_type = entry.get("type")
999
913
  # Narrow to the Literal type — _is_visible_message already guarantees
1000
914
  # this is "user" or "assistant".
1001
- msg_type: Literal["user", "assistant"] = "user" if entry_type == "user" else "assistant"
1002
- return SessionMessage( # pyright: ignore[reportCallIssue]
1003
- type=msg_type,
915
+ return SessionMessage(
916
+ type="user" if entry.get("type") == "user" else "assistant",
1004
917
  uuid=entry.get("uuid", ""),
1005
918
  session_id=entry.get("sessionId", ""),
1006
919
  message=entry.get("message"),
@@ -1030,22 +943,6 @@ def get_session_messages(
1030
943
  List of ``SessionMessage`` objects in chronological order. Returns
1031
944
  an empty list if the session is not found, the session_id is not a
1032
945
  valid UUID, or the transcript contains no visible messages.
1033
-
1034
- Example:
1035
- Read all messages from a session::
1036
-
1037
- messages = get_session_messages(
1038
- "550e8400-e29b-41d4-a716-446655440000",
1039
- directory="/path/to/project",
1040
- )
1041
- for msg in messages:
1042
- print(msg.type, msg.message)
1043
-
1044
- Read with pagination::
1045
-
1046
- page = get_session_messages(
1047
- session_id, limit=10, offset=20
1048
- )
1049
946
  """
1050
947
  if not _validate_uuid(session_id):
1051
948
  return []
@@ -1100,11 +997,7 @@ def _resolve_session_file_path(session_id: str, directory: str | None) -> Path |
1100
997
  if found is not None:
1101
998
  return found
1102
999
 
1103
- try:
1104
- worktree_paths = _get_worktree_paths(canonical_dir)
1105
- except Exception:
1106
- worktree_paths = []
1107
-
1000
+ worktree_paths = _get_worktree_paths(canonical_dir)
1108
1001
  for wt in worktree_paths:
1109
1002
  if wt == canonical_dir:
1110
1003
  continue
@@ -1265,35 +1158,19 @@ def get_subagent_messages(
1265
1158
  an empty list if the session or subagent is not found, the
1266
1159
  session_id is not a valid UUID, or the transcript contains no
1267
1160
  user/assistant messages.
1268
-
1269
- Example:
1270
- Read all messages from a subagent::
1271
-
1272
- messages = get_subagent_messages(
1273
- "550e8400-e29b-41d4-a716-446655440000",
1274
- "abc123",
1275
- directory="/path/to/project",
1276
- )
1277
1161
  """
1278
1162
  if not _validate_uuid(session_id):
1279
1163
  return []
1280
1164
  if not agent_id:
1281
1165
  return []
1282
-
1283
1166
  subagents_dir = _resolve_subagents_dir(session_id, directory)
1284
1167
  if subagents_dir is None:
1285
1168
  return []
1286
-
1287
1169
  # The agent file may be directly in subagents/ or in a nested
1288
1170
  # subdirectory — scan to find it.
1289
- match: Path | None = None
1290
- for found_id, file_path in _collect_agent_files(subagents_dir):
1291
- if found_id == agent_id:
1292
- match = file_path
1293
- break
1171
+ match = next((p for id_, p in _collect_agent_files(subagents_dir) if id_ == agent_id), None)
1294
1172
  if match is None:
1295
1173
  return []
1296
-
1297
1174
  try:
1298
1175
  content = match.read_text(encoding="utf-8")
1299
1176
  except OSError:
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any
12
12
  import anyio
13
13
  import anyio.abc
14
14
  from anyio.streams.text import TextReceiveStream, TextSendStream
15
+ from anyio.to_thread import run_sync
15
16
 
16
17
  from clawd_code_sdk._errors import CLIConnectionError, CLINotFoundError, ProcessError
17
18
  from clawd_code_sdk._internal.transport import Transport
@@ -40,10 +41,7 @@ _DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024 # 1MB buffer limit
40
41
  class SubprocessCLITransport(Transport):
41
42
  """Subprocess transport using Claude Code CLI."""
42
43
 
43
- def __init__(
44
- self,
45
- options: ClaudeAgentOptions | None = None,
46
- ):
44
+ def __init__(self, options: ClaudeAgentOptions | None = None):
47
45
  self._options = options or ClaudeAgentOptions()
48
46
  self._cli_path = str(opts) if (opts := self._options.cli_path) is not None else None
49
47
  self._process: Process | None = None
@@ -76,8 +74,6 @@ class SubprocessCLITransport(Transport):
76
74
 
77
75
  async def connect(self) -> None:
78
76
  """Start subprocess."""
79
- from anyio.to_thread import run_sync
80
-
81
77
  if self._process:
82
78
  return
83
79
  if self._cli_path is None:
@@ -76,6 +76,7 @@ if TYPE_CHECKING:
76
76
  SessionState,
77
77
  UserPrompt,
78
78
  )
79
+ from clawd_code_sdk.models.messages import MessagePriority
79
80
  from clawd_code_sdk.models.system_messages import SDKStatus
80
81
 
81
82
 
@@ -239,6 +240,8 @@ class ClaudeSDKClient:
239
240
  *prompts: str | UserPrompt,
240
241
  session_id: str = "default",
241
242
  parent_tool_use_id: str | None = None,
243
+ should_query: bool = True,
244
+ priority: MessagePriority | None = None,
242
245
  ) -> None:
243
246
  """Send a new user message with one or more content blocks.
244
247
 
@@ -248,6 +251,8 @@ class ClaudeSDKClient:
248
251
  ``query(image_prompt, "What's in this image?")``.
249
252
  session_id: Session identifier for the message.
250
253
  parent_tool_use_id: If responding to a tool use, the tool_use block ID.
254
+ should_query: Whether to query the model for a response. Defaults to True.
255
+ priority: The priority of the message. Defaults to None.
251
256
  """
252
257
  prompt = prompts[0] if prompts else None
253
258
  self._logfire_prompt = str(prompt)
@@ -260,12 +265,20 @@ class ClaudeSDKClient:
260
265
  raise ValueError("At least one prompt is required")
261
266
  # Collect content blocks
262
267
  blocks = [UserTextPrompt(text=p) if isinstance(p, str) else p for p in prompts]
268
+ # message_content = [b.to_content_block() for b in blocks]
269
+ # wire_message = UserMessage(
270
+ # parent_tool_use_id=parent_tool_use_id,
271
+ # session_id=session_id,
272
+ # message=MessageParam(content=message_content),
273
+ # )
263
274
  message_content = [cast(dict[str, Any], b.to_content_block()) for b in blocks]
264
275
  wire_message = {
265
276
  "type": "user",
266
277
  "message": {"role": "user", "content": message_content},
267
278
  "parent_tool_use_id": parent_tool_use_id,
268
279
  "session_id": session_id,
280
+ "should_query": should_query,
281
+ "priority": priority,
269
282
  }
270
283
  await self._query.write_json(wire_message)
271
284
 
@@ -369,6 +369,11 @@ from .system_messages import (
369
369
  SystemMessageUnion,
370
370
  LocalCommandOutputMessage,
371
371
  ElicitationCompleteMessage,
372
+ MemoryRecallSystemMessage,
373
+ MirrorErrorSystemMessage,
374
+ NotificationSystemMessage,
375
+ PluginInstallSystemMessage,
376
+ TaskUpdatedSystemMessage,
372
377
  )
373
378
 
374
379
  from typing import Annotated, Any
@@ -577,8 +582,10 @@ __all__ = [
577
582
  "McpStatusResponse",
578
583
  "McpStdioServerConfig",
579
584
  "McpToolStatus",
585
+ "MemoryRecallSystemMessage",
580
586
  "Message",
581
587
  "MessageParam",
588
+ "MirrorErrorSystemMessage",
582
589
  "MiscMessages",
583
590
  "ModelUsage",
584
591
  "Network",
@@ -587,6 +594,7 @@ __all__ = [
587
594
  "NotebookEditOutput",
588
595
  "NotificationHookInput",
589
596
  "NotificationHookSpecificOutput",
597
+ "NotificationSystemMessage",
590
598
  "OnElicitation",
591
599
  "OnUserQuestion",
592
600
  "OutgoingControlRequest",
@@ -605,6 +613,7 @@ __all__ = [
605
613
  "PermissionUpdateDestination",
606
614
  "Permissions",
607
615
  "PlainTextMediaType",
616
+ "PluginInstallSystemMessage",
608
617
  "PostCompactHookInput",
609
618
  "PostToolUseFailureHookInput",
610
619
  "PostToolUseFailureHookSpecificOutput",
@@ -717,6 +726,7 @@ __all__ = [
717
726
  "TaskProgressUsage",
718
727
  "TaskStartedSystemMessage",
719
728
  "TaskStopOutput",
729
+ "TaskUpdatedSystemMessage",
720
730
  "TeammateIdleHookInput",
721
731
  "TextBlock",
722
732
  "ThinkingBlock",
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
  from collections.abc import Sequence
11
11
  from typing import TYPE_CHECKING, Annotated, Any, Literal, assert_never, cast
12
12
 
13
+ from anthropic.types import Model
13
14
  from anthropic.types.beta.beta_tool_use_block import Caller
14
15
  from pydantic import BaseModel, ConfigDict, Discriminator
15
16
 
@@ -31,6 +32,7 @@ if TYPE_CHECKING:
31
32
  # =============================================================================
32
33
  # Content block types
33
34
  # =============================================================================
35
+ ImageMediaType = Literal["image/jpeg", "image/png", "image/gif", "image/webp"]
34
36
 
35
37
 
36
38
  class BaseContentBlock(BaseModel):
@@ -124,8 +126,8 @@ class ToolResultBlock(BaseContentBlock):
124
126
  class ImageSource(BaseContentBlock):
125
127
  """Base64-encoded image source data."""
126
128
 
127
- type: Literal["base64"]
128
- media_type: str
129
+ type: Literal["base64"] = "base64"
130
+ media_type: ImageMediaType
129
131
  data: str
130
132
 
131
133
 
@@ -198,7 +200,7 @@ class AssistantMessageContent(ClaudeCodeBaseModel):
198
200
  type: Literal["message"] = "message"
199
201
  role: Literal["assistant"] = "assistant"
200
202
  content: Sequence[AssistantContentBlock]
201
- model: str
203
+ model: Model | str
202
204
  stop_reason: StopReason | None = None
203
205
  stop_sequence: str | None = None
204
206
  model_config = ConfigDict(extra="allow")
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  from typing import TYPE_CHECKING, Annotated, Any, Literal, TypedDict, assert_never
6
6
 
7
7
  from pydantic import BaseModel, ConfigDict, Discriminator, Field, TypeAdapter
8
+ from pydantic.alias_generators import to_camel
8
9
 
9
10
  from clawd_code_sdk.models.agents import AgentWireDefinition
10
11
  from clawd_code_sdk.models.base import (
@@ -567,6 +568,7 @@ class SDKControlReadFileResponse(_ControlBase):
567
568
  contents: str
568
569
  abs_path: str
569
570
  truncated: bool | None = None
571
+ model_config = ConfigDict(alias_generator=to_camel)
570
572
 
571
573
 
572
574
  class SDKControlMcpCallRequest(_ControlBase):
@@ -76,6 +76,7 @@ OverAgeDisabledReason = Literal[
76
76
  "no_limits_configured",
77
77
  "unknown",
78
78
  ]
79
+ MessagePriority = Literal["now", "next", "later"]
79
80
 
80
81
 
81
82
  class HumanMessageOrigin(ClaudeCodeBaseModel):
@@ -151,10 +152,22 @@ class BaseMessage(BaseModel):
151
152
  uuid: str
152
153
 
153
154
 
154
- class UserMessage(BaseMessage):
155
+ class FileAttachment(BaseModel):
156
+ """Attachment for a message."""
157
+
158
+ file_uuid: str
159
+ file_name: str
160
+
161
+
162
+ class UserMessage(BaseModel):
155
163
  """User message."""
156
164
 
165
+ model_config = ConfigDict(
166
+ extra="forbid" if IS_DEV else "ignore", arbitrary_types_allowed=True, populate_by_name=True
167
+ )
157
168
  type: Literal["user"] = "user"
169
+ uuid: str | None = None
170
+ """Always set for incoming user messages, can be omitted for objects created in query()."""
158
171
  session_id: str | None = None
159
172
  parent_tool_use_id: str | None = None
160
173
  tool_use_result: (
@@ -162,10 +175,10 @@ class UserMessage(BaseMessage):
162
175
  ) = None
163
176
  is_replay: bool | None = Field(default=None, validation_alias="isReplay")
164
177
  is_synthetic: bool | None = Field(default=None, validation_alias="isSynthetic")
165
- priority: Literal["now", "next", "later"] | None = None
178
+ priority: MessagePriority | None = None
166
179
  message: MessageParam
167
180
  timestamp: str | None = None
168
- file_attachments: list[object] | None = None
181
+ file_attachments: list[FileAttachment] | None = None
169
182
  origin: SDKMessageOrigin | None = None
170
183
  should_query: bool | None = None
171
184
 
@@ -2,9 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from pydantic import BaseModel, Field
5
+ from pydantic import BaseModel, ConfigDict, Field
6
6
 
7
- from clawd_code_sdk.models.base import ClaudeCodeBaseModel
7
+ from clawd_code_sdk.models.base import IS_DEV, ClaudeCodeBaseModel
8
8
 
9
9
 
10
10
  class ModelUsage(ClaudeCodeBaseModel):
@@ -28,9 +28,14 @@ class Usage(BaseModel):
28
28
  """
29
29
 
30
30
  input_tokens: int = 0
31
+ """The number of input tokens which were used."""
31
32
  output_tokens: int = 0
33
+ """The number of output tokens which were used."""
32
34
  cache_creation_input_tokens: int = 0
35
+ """The number of input tokens used to create the cache entry."""
33
36
  cache_read_input_tokens: int = 0
37
+ """The number of input tokens read from the cache."""
38
+ model_config = ConfigDict(extra="forbid" if IS_DEV else "ignore", use_attribute_docstrings=True)
34
39
 
35
40
  @property
36
41
  def total_tokens(self) -> int:
File without changes
File without changes