clawd-code-sdk 1.1.2__tar.gz → 1.1.3__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.2 → clawd_code_sdk-1.1.3}/PKG-INFO +4 -1
  2. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/pyproject.toml +4 -5
  3. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/__init__.py +18 -18
  4. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_internal/sessions.py +244 -0
  5. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_internal/transport/subprocess_cli.py +27 -0
  6. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/client.py +59 -12
  7. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/list_sessions.py +0 -84
  8. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/__init__.py +14 -12
  9. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/control.py +92 -2
  10. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/hooks.py +21 -0
  11. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/options.py +7 -1
  12. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/output_types.py +2 -0
  13. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/session.py +4 -54
  14. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/settings.py +1 -1
  15. clawd_code_sdk-1.1.3/tests/test_session_mutations.py +741 -0
  16. clawd_code_sdk-1.1.3/tests/test_sessions.py +1682 -0
  17. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/.gitignore +0 -0
  18. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/LICENSE +0 -0
  19. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/README.md +0 -0
  20. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_bundled/.gitignore +0 -0
  21. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_errors.py +0 -0
  22. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_internal/__init__.py +0 -0
  23. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_internal/query.py +0 -0
  24. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_internal/session_mutations.py +0 -0
  25. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_internal/transport/__init__.py +0 -0
  26. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_internal/transport/subprocess_utils.py +0 -0
  27. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/_version.py +0 -0
  28. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/anthropic_stream.py +0 -0
  29. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/instrumentation.py +0 -0
  30. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/mcp_utils.py +0 -0
  31. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/agents.py +0 -0
  32. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/anthropic_types.py +0 -0
  33. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/base.py +0 -0
  34. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/content_blocks.py +0 -0
  35. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/context_usage.py +0 -0
  36. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/input_types.py +0 -0
  37. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/mcp.py +0 -0
  38. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/messages.py +0 -0
  39. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/permissions.py +0 -0
  40. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/prompt_requests.py +0 -0
  41. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/prompts.py +0 -0
  42. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/server_info.py +0 -0
  43. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/system_messages.py +0 -0
  44. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/thinking.py +0 -0
  45. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/models/usage.py +0 -0
  46. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/py.typed +0 -0
  47. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/session.py +0 -0
  48. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/storage/ARCHITECTURE.md +0 -0
  49. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/storage/__init__.py +0 -0
  50. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/storage/helpers.py +0 -0
  51. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/storage/models.py +0 -0
  52. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/storage/replay.py +0 -0
  53. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/src/clawd_code_sdk/usage.py +0 -0
  54. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/__init__.py +0 -0
  55. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/conftest.py +0 -0
  56. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/__init__.py +0 -0
  57. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_agents_and_settings.py +0 -0
  58. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_dynamic_control.py +0 -0
  59. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_hook_events.py +0 -0
  60. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_hooks.py +0 -0
  61. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_include_partial_messages.py +0 -0
  62. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_mcp_resources.py +0 -0
  63. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_mcp_tools.py +0 -0
  64. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_sdk_mcp_resources.py +0 -0
  65. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_sdk_mcp_tools.py +0 -0
  66. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_slash_commands.py +0 -0
  67. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_stderr_callback.py +0 -0
  68. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_storage_parsing.py +0 -0
  69. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_structured_output.py +0 -0
  70. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_subagent_invocation.py +0 -0
  71. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/e2e/test_tool_permissions.py +0 -0
  72. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/mcp_server.py +0 -0
  73. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/mock_claude_server.py +0 -0
  74. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_changelog.py +0 -0
  75. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_client.py +0 -0
  76. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_errors.py +0 -0
  77. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_image.png +0 -0
  78. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_integration.py +0 -0
  79. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_message_parser.py +0 -0
  80. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_sdk_mcp_integration.py +0 -0
  81. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_session.py +0 -0
  82. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_streaming_client.py +0 -0
  83. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_subprocess_buffering.py +0 -0
  84. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/tests/test_tool_callbacks.py +0 -0
  85. {clawd_code_sdk-1.1.2 → clawd_code_sdk-1.1.3}/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.2
3
+ Version: 1.1.3
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
@@ -25,12 +25,15 @@ Requires-Dist: mcp>=0.1.0
25
25
  Requires-Dist: python-dotenv>=1.2.1
26
26
  Provides-Extra: dev
27
27
  Requires-Dist: anyio[trio]>=4.0.0; extra == 'dev'
28
+ Requires-Dist: fastmcp>=3.0.0; extra == 'dev'
28
29
  Requires-Dist: mypy>=1.0.0; extra == 'dev'
29
30
  Requires-Dist: pytest-asyncio>=0.20.0; extra == 'dev'
30
31
  Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
31
32
  Requires-Dist: pytest-timeout>=2.4.0; extra == 'dev'
32
33
  Requires-Dist: pytest>=7.0.0; extra == 'dev'
33
34
  Requires-Dist: ruff>=0.1.0; extra == 'dev'
35
+ Provides-Extra: otel
36
+ Requires-Dist: opentelemetry-api>=1.20.0; extra == 'otel'
34
37
  Description-Content-Type: text/markdown
35
38
 
36
39
  # Claude Agent SDK for Python
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "clawd-code-sdk"
3
- version = "1.1.2"
3
+ version = "1.1.3"
4
4
  description = "Python SDK for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -41,12 +41,11 @@ dev = [
41
41
  "pytest-timeout>=2.4.0",
42
42
  "mypy>=1.0.0",
43
43
  "ruff>=0.1.0",
44
- ]
45
-
46
- [dependency-groups]
47
- dev = [
48
44
  "fastmcp>=3.0.0",
49
45
  ]
46
+ otel = [
47
+ "opentelemetry-api>=1.20.0",
48
+ ]
50
49
 
51
50
  [build-system]
52
51
  requires = ["hatchling"]
@@ -21,15 +21,23 @@ from ._errors import (
21
21
  ServerError,
22
22
  )
23
23
  from ._internal.transport import Transport
24
+ from ._internal.sessions import (
25
+ get_session_info,
26
+ get_session_messages,
27
+ get_subagent_messages,
28
+ list_sessions,
29
+ list_subagents,
30
+ )
31
+ from ._internal.session_mutations import tag_session, delete_session, fork_session, rename_session
24
32
  from ._version import __version__
25
33
  from .models.anthropic_types import ToolResultContentBlock
26
34
  from .client import ClaudeSDKClient
27
- from .list_sessions import list_sessions
28
35
  from .models import (
29
36
  AgentDefinition,
30
37
  AgentHookHandler,
31
38
  AgentHooksConfig,
32
39
  ContinueLatest,
40
+ SessionMessage,
33
41
  AssistantMessage,
34
42
  BaseHookInput,
35
43
  CanUseTool,
@@ -47,7 +55,6 @@ from .models import (
47
55
  HookMatcher,
48
56
  HookMatcherConfig,
49
57
  PromptHookHandler,
50
- ListSessionsOptions,
51
58
  McpSdkServerConfig,
52
59
  McpSdkServerConfigWithInstance,
53
60
  McpServerConfig,
@@ -135,11 +142,8 @@ __cli_version__ = "2.1.11"
135
142
 
136
143
 
137
144
  __all__ = [
138
- # API Errors
139
145
  "APIError",
140
- # Agent support
141
146
  "AgentDefinition",
142
- # Hook support
143
147
  "AgentHookHandler",
144
148
  "AgentHooksConfig",
145
149
  "AppliedSettings",
@@ -152,17 +156,13 @@ __all__ = [
152
156
  "CLIConnectionError",
153
157
  "CLIJSONDecodeError",
154
158
  "CLINotFoundError",
155
- # Tool callbacks
156
159
  "CanUseTool",
157
160
  "ClaudeAgentOptions",
158
- # Settings / sandbox
159
161
  "ClaudeCodeSettings",
160
162
  "ClaudeSDKClient",
161
- # Errors
162
163
  "ClaudeSDKError",
163
164
  "CommandHookHandler",
164
165
  "ContentBlock",
165
- # Session config
166
166
  "ContinueLatest",
167
167
  "ConversationTurn",
168
168
  "DocumentMediaType",
@@ -182,7 +182,6 @@ __all__ = [
182
182
  "ImageSource",
183
183
  "InitSystemMessage",
184
184
  "InvalidRequestError",
185
- "ListSessionsOptions",
186
185
  "McpAuthenticateResponse",
187
186
  "McpSdkServerConfig",
188
187
  "McpSdkServerConfigWithInstance",
@@ -194,7 +193,6 @@ __all__ = [
194
193
  "NotificationHookInput",
195
194
  "NotificationHookSpecificOutput",
196
195
  "OnUserQuestion",
197
- # Types
198
196
  "PermissionMode",
199
197
  "PermissionRequestHookInput",
200
198
  "PermissionRequestHookSpecificOutput",
@@ -220,16 +218,14 @@ __all__ = [
220
218
  "ResumeSession",
221
219
  "SDKSessionInfo",
222
220
  "Sandbox",
223
- # Beta support
224
221
  "SdkBeta",
225
222
  "SdkMcpTool",
226
- # Plugin support
227
223
  "SdkPluginConfig",
228
224
  "ServerError",
229
225
  "Session",
230
226
  "SessionConfig",
231
- # Session management
232
227
  "SessionManager",
228
+ "SessionMessage",
233
229
  "SessionSnapshot",
234
230
  "SessionState",
235
231
  "SettingSource",
@@ -240,7 +236,6 @@ __all__ = [
240
236
  "SubagentStopHookInput",
241
237
  "TextBlock",
242
238
  "ThinkingBlock",
243
- # Thinking configuration
244
239
  "ThinkingConfig",
245
240
  "ThinkingConfigAdaptive",
246
241
  "ThinkingConfigDisabled",
@@ -250,7 +245,6 @@ __all__ = [
250
245
  "ToolResultBlock",
251
246
  "ToolResultContentBlock",
252
247
  "ToolUseBlock",
253
- # Transport
254
248
  "Transport",
255
249
  "UserDocumentPrompt",
256
250
  "UserDocumentURLPrompt",
@@ -262,9 +256,15 @@ __all__ = [
262
256
  "UserPromptSubmitHookInput",
263
257
  "UserTextPrompt",
264
258
  "__version__",
265
- # MCP Server Support
266
259
  "create_sdk_mcp_server",
260
+ "delete_session",
261
+ "fork_session",
262
+ "get_session_info",
263
+ "get_session_messages",
264
+ "get_subagent_messages",
267
265
  "list_sessions",
268
- # Main exports
266
+ "list_subagents",
267
+ "rename_session",
268
+ "tag_session",
269
269
  "tool",
270
270
  ]
@@ -1065,3 +1065,247 @@ def get_session_messages(
1065
1065
  if offset > 0:
1066
1066
  return messages[offset:]
1067
1067
  return messages
1068
+
1069
+
1070
+ # ---------------------------------------------------------------------------
1071
+ # list_subagents / get_subagent_messages — subagent transcript reading
1072
+ # ---------------------------------------------------------------------------
1073
+
1074
+
1075
+ def _resolve_session_file_path(session_id: str, directory: str | None) -> Path | None:
1076
+ """Resolves the on-disk path of a session JSONL file.
1077
+
1078
+ Directory resolution mirrors ``_read_session_file``: when ``directory``
1079
+ is provided, looks in that project directory and its git worktrees;
1080
+ otherwise searches all project directories. Returns the path of the
1081
+ first non-empty match, or ``None`` if not found.
1082
+ """
1083
+ file_name = f"{session_id}.jsonl"
1084
+
1085
+ def _stat_candidate(project_dir: Path) -> Path | None:
1086
+ candidate = project_dir / file_name
1087
+ try:
1088
+ if candidate.stat().st_size > 0:
1089
+ return candidate
1090
+ except OSError:
1091
+ pass
1092
+ return None
1093
+
1094
+ if directory:
1095
+ canonical_dir = _canonicalize_path(directory)
1096
+
1097
+ project_dir = _find_project_dir(canonical_dir)
1098
+ if project_dir is not None:
1099
+ found = _stat_candidate(project_dir)
1100
+ if found is not None:
1101
+ return found
1102
+
1103
+ try:
1104
+ worktree_paths = _get_worktree_paths(canonical_dir)
1105
+ except Exception:
1106
+ worktree_paths = []
1107
+
1108
+ for wt in worktree_paths:
1109
+ if wt == canonical_dir:
1110
+ continue
1111
+ wt_project_dir = _find_project_dir(wt)
1112
+ if wt_project_dir is not None:
1113
+ found = _stat_candidate(wt_project_dir)
1114
+ if found is not None:
1115
+ return found
1116
+
1117
+ return None
1118
+
1119
+ projects_dir = _get_projects_dir()
1120
+ try:
1121
+ dirents = list(projects_dir.iterdir())
1122
+ except OSError:
1123
+ return None
1124
+
1125
+ for entry in dirents:
1126
+ if not entry.is_dir():
1127
+ continue
1128
+ found = _stat_candidate(entry)
1129
+ if found is not None:
1130
+ return found
1131
+
1132
+ return None
1133
+
1134
+
1135
+ def _resolve_subagents_dir(session_id: str, directory: str | None) -> Path | None:
1136
+ """Resolves the subagents directory for a given session.
1137
+
1138
+ The session file lives at ``<projectDir>/<sessionId>.jsonl`` and the
1139
+ subagents directory at ``<projectDir>/<sessionId>/subagents/``.
1140
+
1141
+ Returns ``None`` if the session cannot be found.
1142
+ """
1143
+ resolved = _resolve_session_file_path(session_id, directory)
1144
+ if resolved is None:
1145
+ return None
1146
+ # Strip the .jsonl suffix to derive the session directory.
1147
+ session_dir = resolved.with_suffix("")
1148
+ return session_dir / "subagents"
1149
+
1150
+
1151
+ def _collect_agent_files(base_dir: Path) -> list[tuple[str, Path]]:
1152
+ """Recursively collects ``agent-*.jsonl`` files from a directory tree.
1153
+
1154
+ Subagent transcripts may live directly in ``subagents/`` or in nested
1155
+ subdirectories such as ``subagents/workflows/<runId>/``.
1156
+
1157
+ Returns a list of ``(agent_id, file_path)`` tuples.
1158
+ """
1159
+ results: list[tuple[str, Path]] = []
1160
+
1161
+ def _walk(current_dir: Path) -> None:
1162
+ try:
1163
+ dirents = sorted(current_dir.iterdir(), key=lambda p: p.name)
1164
+ except OSError:
1165
+ return
1166
+ for entry in dirents:
1167
+ name = entry.name
1168
+ if entry.is_file() and name.startswith("agent-") and name.endswith(".jsonl"):
1169
+ agent_id = name[len("agent-") : -len(".jsonl")]
1170
+ results.append((agent_id, entry))
1171
+ elif entry.is_dir():
1172
+ _walk(entry)
1173
+
1174
+ _walk(base_dir)
1175
+ return results
1176
+
1177
+
1178
+ def _build_subagent_chain(entries: list[_TranscriptEntry]) -> list[_TranscriptEntry]:
1179
+ """Builds the conversation chain for a subagent transcript.
1180
+
1181
+ Subagent transcripts are simpler than main sessions — no compaction,
1182
+ no sidechains, no preserved segments. Find the last user/assistant
1183
+ entry and walk ``parentUuid`` links back to the root.
1184
+ """
1185
+ if not entries:
1186
+ return []
1187
+ by_uuid = {e["uuid"]: e for e in entries}
1188
+ leaf = next((e for e in reversed(entries) if e.get("type") in ("user", "assistant")), None)
1189
+ if leaf is None:
1190
+ return []
1191
+ chain: list[_TranscriptEntry] = []
1192
+ seen: set[str] = set()
1193
+ current: _TranscriptEntry | None = leaf
1194
+ while current is not None:
1195
+ uid = current["uuid"]
1196
+ if uid in seen:
1197
+ break
1198
+ seen.add(uid)
1199
+ chain.append(current)
1200
+ parent = current.get("parentUuid")
1201
+ current = by_uuid.get(parent) if parent else None
1202
+
1203
+ chain.reverse()
1204
+ return chain
1205
+
1206
+
1207
+ def list_subagents(session_id: str, directory: str | None = None) -> list[str]:
1208
+ """Lists subagent IDs for a given session by scanning the subagents directory.
1209
+
1210
+ Subagent transcripts are stored at
1211
+ ``~/.claude/projects/<project>/<sessionId>/subagents/agent-<agentId>.jsonl``
1212
+ (and may be nested in subdirectories such as ``workflows/<runId>/``).
1213
+
1214
+ Args:
1215
+ session_id: UUID of the parent session.
1216
+ directory: Project directory to find the session in. If omitted,
1217
+ searches all project directories under ``~/.claude/projects/``.
1218
+
1219
+ Returns:
1220
+ List of subagent ID strings. Returns an empty list if the session
1221
+ is not found, the session_id is not a valid UUID, or the session
1222
+ has no subagents.
1223
+
1224
+ Example:
1225
+ List subagent IDs for a session::
1226
+
1227
+ agent_ids = list_subagents(
1228
+ "550e8400-e29b-41d4-a716-446655440000",
1229
+ directory="/path/to/project",
1230
+ )
1231
+ """
1232
+ if not _validate_uuid(session_id):
1233
+ return []
1234
+
1235
+ subagents_dir = _resolve_subagents_dir(session_id, directory)
1236
+ if subagents_dir is None:
1237
+ return []
1238
+
1239
+ return [agent_id for agent_id, _ in _collect_agent_files(subagents_dir)]
1240
+
1241
+
1242
+ def get_subagent_messages(
1243
+ session_id: str,
1244
+ agent_id: str,
1245
+ directory: str | None = None,
1246
+ limit: int | None = None,
1247
+ offset: int = 0,
1248
+ ) -> list[SessionMessage]:
1249
+ """Reads a subagent's conversation messages from its JSONL transcript file.
1250
+
1251
+ Parses the subagent transcript, builds the conversation chain via
1252
+ ``parentUuid`` links, and returns user/assistant messages in
1253
+ chronological order.
1254
+
1255
+ Args:
1256
+ session_id: UUID of the parent session.
1257
+ agent_id: ID of the subagent (as returned by ``list_subagents``).
1258
+ directory: Project directory to find the session in. If omitted,
1259
+ searches all project directories under ``~/.claude/projects/``.
1260
+ limit: Maximum number of messages to return.
1261
+ offset: Number of messages to skip from the start.
1262
+
1263
+ Returns:
1264
+ List of ``SessionMessage`` objects in chronological order. Returns
1265
+ an empty list if the session or subagent is not found, the
1266
+ session_id is not a valid UUID, or the transcript contains no
1267
+ 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
+ """
1278
+ if not _validate_uuid(session_id):
1279
+ return []
1280
+ if not agent_id:
1281
+ return []
1282
+
1283
+ subagents_dir = _resolve_subagents_dir(session_id, directory)
1284
+ if subagents_dir is None:
1285
+ return []
1286
+
1287
+ # The agent file may be directly in subagents/ or in a nested
1288
+ # 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
1294
+ if match is None:
1295
+ return []
1296
+
1297
+ try:
1298
+ content = match.read_text(encoding="utf-8")
1299
+ except OSError:
1300
+ return []
1301
+ if not content:
1302
+ return []
1303
+
1304
+ entries = _parse_transcript_entries(content)
1305
+ chain = _build_subagent_chain(entries)
1306
+ messages = [_to_session_message(e) for e in chain if e.get("type") in ("user", "assistant")]
1307
+ if limit is not None and limit > 0:
1308
+ return messages[offset : offset + limit]
1309
+ if offset > 0:
1310
+ return messages[offset:]
1311
+ return messages
@@ -96,6 +96,33 @@ class SubprocessCLITransport(Transport):
96
96
  # "CLAUDE_CODE_SDK_VERSION": "xyz",
97
97
  **get_env_vars(self._options),
98
98
  }
99
+
100
+ # Propagate active OTEL trace context to the CLI so its spans
101
+ # parent under the caller's distributed trace. No-op if
102
+ # opentelemetry-api is not installed or there's no active span.
103
+ try:
104
+ from opentelemetry import propagate
105
+
106
+ carrier: dict[str, str] = {}
107
+ propagate.inject(carrier)
108
+ if "traceparent" in carrier:
109
+ # Active span present: scrub stale inherited W3C context
110
+ # (CI/k8s ambient env) before writing the fresh values, so
111
+ # an inherited TRACESTATE isn't paired with a new
112
+ # TRACEPARENT. Explicit ClaudeAgentOptions.env always wins.
113
+ # Gate on the traceparent key (not carrier truthiness) so a
114
+ # baggage-only / non-W3C carrier doesn't scrub a valid
115
+ # inherited TRACEPARENT.
116
+ for key in ("TRACEPARENT", "TRACESTATE"):
117
+ if key not in self._options.env:
118
+ process_env.pop(key, None)
119
+ for k, v in carrier.items():
120
+ key = k.upper()
121
+ if key not in self._options.env:
122
+ process_env[key] = v
123
+ except Exception:
124
+ logger.debug("OTEL trace context injection failed", exc_info=True)
125
+
99
126
  # Always pipe stderr so we can capture it for error reporting.
100
127
  # The callback and debug mode flags control whether lines are
101
128
  # forwarded in real-time, but we always collect them.
@@ -20,6 +20,7 @@ from clawd_code_sdk.models import (
20
20
  McpAuthenticateResponse,
21
21
  McpSetServersResult,
22
22
  McpStatusResponse,
23
+ NewSession,
23
24
  RemoteControlResponse,
24
25
  ResultErrorMessage,
25
26
  ResultSuccessMessage,
@@ -34,12 +35,15 @@ from clawd_code_sdk.models import (
34
35
  SDKControlInitializeRequest,
35
36
  SDKControlInterruptRequest,
36
37
  SDKControlMcpAuthenticateRequest,
38
+ SDKControlMcpCallRequest,
37
39
  SDKControlMcpClearAuthRequest,
38
40
  SDKControlMcpOAuthCallbackUrlRequest,
39
41
  SDKControlMcpReconnectRequest,
40
42
  SDKControlMcpSetServersRequest,
41
43
  SDKControlMcpStatusRequest,
42
44
  SDKControlMcpToggleRequest,
45
+ SDKControlReadFileRequest,
46
+ SDKControlReadFileResponse,
43
47
  SDKControlRemoteControlRequest,
44
48
  SDKControlRewindFilesRequest,
45
49
  SDKControlSeedReadStateRequest,
@@ -162,22 +166,34 @@ class ClaudeSDKClient:
162
166
  """Send the initialize control request to the CLI."""
163
167
  query = self._ensure_connected()
164
168
  options = self.options
165
-
166
- # Resolve system prompt vs append_system_prompt from options
167
- system_prompt: str | None = None
168
- append_system_prompt: str | None = None
169
- if options.system_prompt is None:
170
- if not options.include_builtin_system_prompt:
171
- system_prompt = "" # Clear the builtin prompt
172
- elif options.include_builtin_system_prompt:
173
- append_system_prompt = options.system_prompt
174
- else:
175
- system_prompt = options.system_prompt
169
+ match options.system_prompt, options.include_builtin_system_prompt:
170
+ case None, False:
171
+ system_prompt: list[str] | None = [""] # Clear the builtin prompt
172
+ append_system_prompt: str | None = None
173
+ case None, True:
174
+ system_prompt = None # Use the builtin prompt
175
+ append_system_prompt = None
176
+ case str() as prompt_str, True:
177
+ system_prompt = None
178
+ append_system_prompt = prompt_str
179
+ case list() as prompt_list, True:
180
+ system_prompt = None
181
+ append_system_prompt = "\n".join(prompt_list)
182
+ case str() as prompt_str, False:
183
+ system_prompt = [prompt_str]
184
+ append_system_prompt = None
185
+ case list() as prompt_list, False:
186
+ system_prompt = prompt_list
187
+ append_system_prompt = None
176
188
 
177
189
  # Calculate initialize timeout
178
190
  initialize_timeout_ms = int(os.environ.get("CLAUDE_CODE_STREAM_CLOSE_TIMEOUT", "60000"))
179
191
  initialize_timeout = max(initialize_timeout_ms / 1000.0, 60.0)
180
-
192
+ match options.get_session():
193
+ case NewSession() as s:
194
+ title = s.title
195
+ case _:
196
+ title = None
181
197
  hooks_config = query.build_hooks_config()
182
198
  request = SDKControlInitializeRequest(
183
199
  hooks=hooks_config,
@@ -189,6 +205,8 @@ class ClaudeSDKClient:
189
205
  exclude_dynamic_sections=options.exclude_dynamic_sections,
190
206
  sdk_mcp_servers=list(query.sdk_mcp_servers.keys()) or None,
191
207
  agent_progress_summaries=options.agent_progress_summaries,
208
+ title=title,
209
+ skills=options.skills,
192
210
  )
193
211
  response = await query._send_control_request(request, timeout=initialize_timeout)
194
212
  self._initialization_result = ClaudeCodeServerInfo.model_validate(response)
@@ -523,6 +541,35 @@ class ClaudeSDKClient:
523
541
  raise RuntimeError("Not initialized. Call connect() first.")
524
542
  return self._initialization_result.agents
525
543
 
544
+ async def get_file(self, path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse:
545
+ """Get the contents of a file from the server.
546
+
547
+ Args:
548
+ path: Path to the file to read
549
+ max_bytes: Maximum number of bytes to read (default: None, no limit)
550
+
551
+ Returns:
552
+ The file contents and metadata
553
+ """
554
+ query = self._ensure_connected()
555
+ request = SDKControlReadFileRequest(path=path, max_bytes=max_bytes)
556
+ result = await query._send_control_request(request)
557
+ return SDKControlReadFileResponse.model_validate(result)
558
+
559
+ async def call_tool(self, tool: str, arguments: dict[str, Any] | None = None) -> Any:
560
+ """Call a tool on the server.
561
+
562
+ Args:
563
+ tool: The name of the tool to call
564
+ arguments: Optional dictionary of arguments for the tool
565
+
566
+ Returns:
567
+ The result of the tool call
568
+ """
569
+ query = self._ensure_connected()
570
+ request = SDKControlMcpCallRequest(tool=tool, arguments=arguments)
571
+ return await query._send_control_request(request)
572
+
526
573
  async def get_server_info(self) -> ClaudeCodeServerInfo | None:
527
574
  """Get server initialization info including available commands and output styles.
528
575
 
@@ -4,19 +4,9 @@ from __future__ import annotations
4
4
 
5
5
  import logging
6
6
  from pathlib import Path # noqa: TC003
7
- from typing import TYPE_CHECKING
8
7
 
9
8
  import anyenv
10
9
 
11
- from clawd_code_sdk.storage.helpers import (
12
- decode_project_path,
13
- get_claude_projects_dir,
14
- path_to_claude_dir_name,
15
- )
16
-
17
-
18
- if TYPE_CHECKING:
19
- from clawd_code_sdk.models import ListSessionsOptions, SDKSessionInfo
20
10
 
21
11
  logger = logging.getLogger(__name__)
22
12
 
@@ -105,77 +95,3 @@ def _extract_session_metadata(session_path: Path) -> tuple[str | None, str | Non
105
95
  pass
106
96
 
107
97
  return custom_title, first_prompt
108
-
109
-
110
- def _list_session_files_for_dir(directory: str) -> list[tuple[Path, str | None]]:
111
- """List session files for a specific project directory.
112
-
113
- Args:
114
- directory: Filesystem path of the project.
115
-
116
- Returns:
117
- List of ``(session_path, cwd)`` tuples.
118
- """
119
- projects_dir = get_claude_projects_dir()
120
- dir_name = path_to_claude_dir_name(directory)
121
- project_dir = projects_dir / dir_name
122
- if not project_dir.is_dir():
123
- return []
124
- return [(p, directory) for p in project_dir.glob("*.jsonl")]
125
-
126
-
127
- def _list_all_session_files() -> list[tuple[Path, str | None]]:
128
- """List session files across all projects.
129
-
130
- Returns:
131
- List of ``(session_path, cwd)`` tuples where cwd is decoded
132
- from the project directory name.
133
- """
134
- projects_dir = get_claude_projects_dir()
135
- if not projects_dir.is_dir():
136
- return []
137
- results: list[tuple[Path, str | None]] = []
138
- for project_dir in projects_dir.iterdir():
139
- if not project_dir.is_dir():
140
- continue
141
- cwd = decode_project_path(project_dir.name)
142
- for session_file in project_dir.glob("*.jsonl"):
143
- results.append((session_file, cwd)) # noqa: PERF401
144
- return results
145
-
146
-
147
- def list_sessions(options: ListSessionsOptions | None = None) -> list[SDKSessionInfo]:
148
- """List sessions with metadata.
149
-
150
- When ``dir`` is provided in *options*, returns sessions for that project
151
- directory and its git worktrees. When omitted, returns sessions across
152
- all projects.
153
-
154
- Args:
155
- options: Optional filtering/limiting options.
156
-
157
- Returns:
158
- Session metadata sorted by last modified time (newest first).
159
-
160
- Example::
161
-
162
- from clawd_code_sdk import list_sessions
163
-
164
- # List sessions for a specific project
165
- sessions = list_sessions({"dir": "/path/to/project"})
166
-
167
- # List all sessions across all projects
168
- all_sessions = list_sessions()
169
- """
170
- from clawd_code_sdk.models import SDKSessionInfo
171
-
172
- opts = options or {}
173
- dir_ = opts.get("dir")
174
- limit = opts.get("limit")
175
- # Collect session files
176
- files = _list_all_session_files() if dir_ is None else _list_session_files_for_dir(dir_)
177
- sessions = [SDKSessionInfo.from_session_file(p, cwd) for p, cwd in files if p.exists()]
178
- sessions.sort(key=lambda s: s.last_modified, reverse=True)
179
- if limit is not None and limit > 0:
180
- sessions = sessions[:limit]
181
- return sessions