clawd-code-sdk 1.1.0__tar.gz → 1.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/PKG-INFO +1 -1
  2. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/pyproject.toml +1 -1
  3. clawd_code_sdk-1.1.2/src/clawd_code_sdk/_internal/session_mutations.py +663 -0
  4. clawd_code_sdk-1.1.2/src/clawd_code_sdk/_internal/sessions.py +1067 -0
  5. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/client.py +3 -2
  6. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/base.py +3 -2
  7. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/context_usage.py +1 -0
  8. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/control.py +17 -0
  9. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/input_types.py +5 -0
  10. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/mcp.py +8 -1
  11. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/messages.py +46 -3
  12. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/output_types.py +1 -0
  13. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/session.py +2 -1
  14. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/settings.py +14 -2
  15. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/system_messages.py +104 -18
  16. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/storage/replay.py +23 -13
  17. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/.gitignore +0 -0
  18. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/LICENSE +0 -0
  19. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/README.md +0 -0
  20. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/__init__.py +0 -0
  21. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_bundled/.gitignore +0 -0
  22. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_errors.py +0 -0
  23. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_internal/__init__.py +0 -0
  24. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_internal/query.py +0 -0
  25. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_internal/transport/__init__.py +0 -0
  26. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_internal/transport/subprocess_cli.py +0 -0
  27. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_internal/transport/subprocess_utils.py +0 -0
  28. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/_version.py +0 -0
  29. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/anthropic_stream.py +0 -0
  30. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/instrumentation.py +0 -0
  31. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/list_sessions.py +0 -0
  32. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/mcp_utils.py +0 -0
  33. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/__init__.py +0 -0
  34. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/agents.py +0 -0
  35. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/anthropic_types.py +0 -0
  36. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/content_blocks.py +0 -0
  37. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/hooks.py +0 -0
  38. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/options.py +0 -0
  39. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/permissions.py +0 -0
  40. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/prompt_requests.py +0 -0
  41. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/prompts.py +0 -0
  42. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/server_info.py +0 -0
  43. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/thinking.py +0 -0
  44. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/models/usage.py +0 -0
  45. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/py.typed +0 -0
  46. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/session.py +0 -0
  47. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/storage/ARCHITECTURE.md +0 -0
  48. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/storage/__init__.py +0 -0
  49. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/storage/helpers.py +0 -0
  50. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/storage/models.py +0 -0
  51. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/src/clawd_code_sdk/usage.py +0 -0
  52. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/__init__.py +0 -0
  53. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/conftest.py +0 -0
  54. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/__init__.py +0 -0
  55. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_agents_and_settings.py +0 -0
  56. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_dynamic_control.py +0 -0
  57. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_hook_events.py +0 -0
  58. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_hooks.py +0 -0
  59. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_include_partial_messages.py +0 -0
  60. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_mcp_resources.py +0 -0
  61. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_mcp_tools.py +0 -0
  62. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_sdk_mcp_resources.py +0 -0
  63. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_sdk_mcp_tools.py +0 -0
  64. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_slash_commands.py +0 -0
  65. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_stderr_callback.py +0 -0
  66. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_storage_parsing.py +0 -0
  67. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_structured_output.py +0 -0
  68. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_subagent_invocation.py +0 -0
  69. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/e2e/test_tool_permissions.py +0 -0
  70. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/mcp_server.py +0 -0
  71. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/mock_claude_server.py +0 -0
  72. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_changelog.py +0 -0
  73. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_client.py +0 -0
  74. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_errors.py +0 -0
  75. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_image.png +0 -0
  76. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_integration.py +0 -0
  77. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_message_parser.py +0 -0
  78. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_sdk_mcp_integration.py +0 -0
  79. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_session.py +0 -0
  80. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_streaming_client.py +0 -0
  81. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_subprocess_buffering.py +0 -0
  82. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/tests/test_tool_callbacks.py +0 -0
  83. {clawd_code_sdk-1.1.0 → clawd_code_sdk-1.1.2}/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.0
3
+ Version: 1.1.2
4
4
  Summary: Python SDK for Claude Code
5
5
  Project-URL: Documentation, https://github.com/phil65/claude-agent-sdk-python
6
6
  Project-URL: Homepage, https://github.com/phil65/claude-agent-sdk-python
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "clawd-code-sdk"
3
- version = "1.1.0"
3
+ version = "1.1.2"
4
4
  description = "Python SDK for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -0,0 +1,663 @@
1
+ """Portable session mutation functions for the Agent SDK.
2
+
3
+ Rename/tag append typed metadata entries to the session's JSONL (matching
4
+ the CLI pattern); delete removes the JSONL file; fork creates a new session
5
+ with UUID remapping. Safe to call from any SDK host process — see
6
+ concurrent-writer note below.
7
+
8
+ Directory resolution matches list_sessions / get_session_messages:
9
+ ``directory`` is the project path (not the storage dir); when omitted, all
10
+ project directories are searched for the session file.
11
+
12
+ Concurrent writers: if the target session is currently open in a CLI
13
+ process, the CLI's reAppendSessionMetadata() tail-reads before re-appending
14
+ its cached metadata. If an SDK write (e.g. a custom-title entry) is in the
15
+ tail scan window, the CLI absorbs it into its cache and re-appends the SDK
16
+ value — not the stale CLI value.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass
22
+ from datetime import UTC, datetime
23
+ import errno
24
+ import json
25
+ import os
26
+ import re
27
+ import shutil
28
+ from typing import TYPE_CHECKING, Any
29
+ import unicodedata
30
+ import uuid as uuid_mod
31
+
32
+ import anyenv
33
+
34
+ from .sessions import (
35
+ LITE_READ_BUF_SIZE,
36
+ _canonicalize_path,
37
+ _extract_first_prompt_from_head,
38
+ _extract_last_json_string_field,
39
+ _find_project_dir,
40
+ _get_projects_dir,
41
+ _get_worktree_paths,
42
+ _validate_uuid,
43
+ )
44
+
45
+
46
+ if TYPE_CHECKING:
47
+ from pathlib import Path
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Public API
52
+ # ---------------------------------------------------------------------------
53
+
54
+
55
+ def rename_session(
56
+ session_id: str,
57
+ title: str,
58
+ directory: str | None = None,
59
+ ) -> None:
60
+ """Rename a session by appending a custom-title entry.
61
+
62
+ ``list_sessions`` reads the LAST custom-title from the file tail, so
63
+ repeated calls are safe — the most recent wins.
64
+
65
+ Args:
66
+ session_id: UUID of the session to rename.
67
+ title: New session title. Leading/trailing whitespace is stripped.
68
+ Must be non-empty after stripping.
69
+ directory: Project directory path (same semantics as
70
+ ``list_sessions(directory=...)``). When omitted, all project
71
+ directories are searched for the session file.
72
+
73
+ Raises:
74
+ ValueError: If ``session_id`` is not a valid UUID, or if ``title``
75
+ is empty/whitespace-only.
76
+ FileNotFoundError: If the session file cannot be found.
77
+
78
+ Example:
79
+ Rename a session in a specific project::
80
+
81
+ rename_session(
82
+ "550e8400-e29b-41d4-a716-446655440000",
83
+ "My refactoring session",
84
+ directory="/path/to/project",
85
+ )
86
+ """
87
+ if not _validate_uuid(session_id):
88
+ raise ValueError(f"Invalid session_id: {session_id}")
89
+ # Matches CLI guard — empty/whitespace titles are rejected rather than
90
+ # overloaded as "clear title".
91
+ stripped = title.strip()
92
+ if not stripped:
93
+ raise ValueError("title must be non-empty")
94
+
95
+ data = (
96
+ json.dumps(
97
+ {
98
+ "type": "custom-title",
99
+ "customTitle": stripped,
100
+ "sessionId": session_id,
101
+ },
102
+ separators=(",", ":"),
103
+ )
104
+ + "\n"
105
+ )
106
+
107
+ _append_to_session(session_id, data, directory)
108
+
109
+
110
+ def tag_session(
111
+ session_id: str,
112
+ tag: str | None,
113
+ directory: str | None = None,
114
+ ) -> None:
115
+ """Tag a session. Pass ``None`` to clear the tag.
116
+
117
+ Appends a ``{type:'tag',tag:<tag>,sessionId:<id>}`` JSONL entry.
118
+ ``list_sessions`` reads the LAST tag from the file tail — most recent
119
+ wins. Passing ``None`` appends an empty-string tag entry which
120
+ ``list_sessions`` treats as ``None`` (cleared).
121
+
122
+ Tags are Unicode-sanitized before storing (removes zero-width chars,
123
+ directional marks, private-use characters, etc.) for CLI filter
124
+ compatibility.
125
+
126
+ Args:
127
+ session_id: UUID of the session to tag.
128
+ tag: Tag string, or ``None`` to clear. Leading/trailing whitespace
129
+ is stripped. Must be non-empty after sanitization and stripping
130
+ (unless ``None``).
131
+ directory: Project directory path (same semantics as
132
+ ``list_sessions(directory=...)``). When omitted, all project
133
+ directories are searched for the session file.
134
+
135
+ Raises:
136
+ ValueError: If ``session_id`` is not a valid UUID, or if ``tag`` is
137
+ empty/whitespace-only after sanitization.
138
+ FileNotFoundError: If the session file cannot be found.
139
+
140
+ Example:
141
+ Tag a session::
142
+
143
+ tag_session(
144
+ "550e8400-e29b-41d4-a716-446655440000",
145
+ "experiment",
146
+ directory="/path/to/project",
147
+ )
148
+
149
+ Clear a tag::
150
+
151
+ tag_session(session_id, None)
152
+ """
153
+ if not _validate_uuid(session_id):
154
+ raise ValueError(f"Invalid session_id: {session_id}")
155
+ if tag is not None:
156
+ sanitized = _sanitize_unicode(tag).strip()
157
+ if not sanitized:
158
+ raise ValueError("tag must be non-empty (use None to clear)")
159
+ tag = sanitized
160
+
161
+ data = (
162
+ json.dumps(
163
+ {
164
+ "type": "tag",
165
+ "tag": tag if tag is not None else "",
166
+ "sessionId": session_id,
167
+ },
168
+ separators=(",", ":"),
169
+ )
170
+ + "\n"
171
+ )
172
+
173
+ _append_to_session(session_id, data, directory)
174
+
175
+
176
+ def delete_session(
177
+ session_id: str,
178
+ directory: str | None = None,
179
+ ) -> None:
180
+ """Delete a session by removing its JSONL file and subagent transcripts.
181
+
182
+ This is a hard delete — the ``{session_id}.jsonl`` file is removed
183
+ permanently, along with the sibling ``{session_id}/`` subdirectory that
184
+ holds subagent transcripts (if it exists). SDK users who need soft-delete
185
+ semantics can use ``tag_session(id, '__hidden')`` and filter on listing
186
+ instead.
187
+
188
+ Args:
189
+ session_id: UUID of the session to delete.
190
+ directory: Project directory path (same semantics as
191
+ ``list_sessions(directory=...)``). When omitted, all project
192
+ directories are searched for the session file.
193
+
194
+ Raises:
195
+ ValueError: If ``session_id`` is not a valid UUID.
196
+ FileNotFoundError: If the session file cannot be found.
197
+
198
+ Example:
199
+ Delete a session::
200
+
201
+ delete_session("550e8400-e29b-41d4-a716-446655440000")
202
+ """
203
+ if not _validate_uuid(session_id):
204
+ raise ValueError(f"Invalid session_id: {session_id}")
205
+
206
+ path = _find_session_file(session_id, directory)
207
+ if path is None:
208
+ raise FileNotFoundError(
209
+ f"Session {session_id} not found"
210
+ + (f" in project directory for {directory}" if directory else "")
211
+ )
212
+ try:
213
+ path.unlink()
214
+ except OSError as e:
215
+ if e.errno == errno.ENOENT:
216
+ raise FileNotFoundError(f"Session {session_id} not found") from e
217
+ raise
218
+ # Subagent transcripts live in a sibling {session_id}/ dir; often absent.
219
+ shutil.rmtree(path.parent / session_id, ignore_errors=True)
220
+
221
+
222
+ @dataclass
223
+ class ForkSessionResult:
224
+ """Result of a fork operation."""
225
+
226
+ session_id: str
227
+ """UUID of the new forked session."""
228
+
229
+
230
+ def fork_session(
231
+ session_id: str,
232
+ directory: str | None = None,
233
+ up_to_message_id: str | None = None,
234
+ title: str | None = None,
235
+ ) -> ForkSessionResult:
236
+ """Fork a session into a new branch with fresh UUIDs.
237
+
238
+ Copies transcript messages from the source session into a new session
239
+ file, remapping every message UUID and preserving the ``parentUuid``
240
+ chain. Supports ``up_to_message_id`` for branching from a specific
241
+ point in the conversation.
242
+
243
+ Forked sessions start without undo history (file-history snapshots are
244
+ not copied).
245
+
246
+ Args:
247
+ session_id: UUID of the source session to fork.
248
+ directory: Project directory path (same semantics as
249
+ ``list_sessions(directory=...)``). When omitted, all project
250
+ directories are searched for the session file.
251
+ up_to_message_id: Slice transcript up to this message UUID
252
+ (inclusive). If omitted, copies the full transcript.
253
+ title: Custom title for the fork. If omitted, derives from
254
+ the original title + " (fork)".
255
+
256
+ Returns:
257
+ ``ForkSessionResult`` with the new session's UUID.
258
+
259
+ Raises:
260
+ ValueError: If ``session_id`` or ``up_to_message_id`` is not a
261
+ valid UUID.
262
+ FileNotFoundError: If the source session file cannot be found.
263
+ ValueError: If the session has no messages to fork, or if
264
+ ``up_to_message_id`` is not found in the transcript.
265
+
266
+ Example:
267
+ Fork a session::
268
+
269
+ result = fork_session("550e8400-e29b-41d4-a716-446655440000")
270
+ print(result.session_id)
271
+
272
+ Fork from a specific point::
273
+
274
+ result = fork_session(
275
+ "550e8400-e29b-41d4-a716-446655440000",
276
+ up_to_message_id="660e8400-e29b-41d4-a716-446655440001",
277
+ )
278
+ """
279
+ if not _validate_uuid(session_id):
280
+ raise ValueError(f"Invalid session_id: {session_id}")
281
+ if up_to_message_id and not _validate_uuid(up_to_message_id):
282
+ raise ValueError(f"Invalid up_to_message_id: {up_to_message_id}")
283
+
284
+ source = _find_session_file_with_dir(session_id, directory)
285
+ if source is None:
286
+ raise FileNotFoundError(
287
+ f"Session {session_id} not found"
288
+ + (f" in project directory for {directory}" if directory else "")
289
+ )
290
+ file_path, project_dir = source
291
+
292
+ content = file_path.read_bytes()
293
+ if not content:
294
+ raise ValueError(f"Session {session_id} has no messages to fork")
295
+
296
+ transcript, content_replacements = _parse_fork_transcript(content, session_id)
297
+
298
+ # Filter out sidechains (subagent sessions with separate parentUuid
299
+ # graphs). Keep isMeta entries — they're interleaved in the main chain.
300
+ transcript = [e for e in transcript if not e.get("isSidechain")]
301
+
302
+ if not transcript:
303
+ raise ValueError(f"Session {session_id} has no messages to fork")
304
+
305
+ if up_to_message_id:
306
+ cutoff = -1
307
+ for i, entry in enumerate(transcript):
308
+ if entry.get("uuid") == up_to_message_id:
309
+ cutoff = i
310
+ break
311
+ if cutoff == -1:
312
+ raise ValueError(f"Message {up_to_message_id} not found in session {session_id}")
313
+ transcript = transcript[: cutoff + 1]
314
+
315
+ # Include progress entries in the mapping — needed for parentUuid chain walk.
316
+ uuid_mapping: dict[str, str] = {}
317
+ for entry in transcript:
318
+ uuid_mapping[entry["uuid"]] = str(uuid_mod.uuid4())
319
+
320
+ # Filter out progress messages from written output. They're UI-only
321
+ # chain links; not needed in a fresh fork.
322
+ writable = [e for e in transcript if e.get("type") != "progress"]
323
+ if not writable:
324
+ raise ValueError(f"Session {session_id} has no messages to fork")
325
+
326
+ by_uuid: dict[str, dict[str, Any]] = {}
327
+ for entry in transcript:
328
+ by_uuid[entry["uuid"]] = entry
329
+
330
+ forked_session_id = str(uuid_mod.uuid4())
331
+
332
+ now = datetime.now(UTC).isoformat().replace("+00:00", "Z")
333
+ lines: list[str] = []
334
+
335
+ for i, original in enumerate(writable):
336
+ new_uuid = uuid_mapping[original["uuid"]]
337
+
338
+ # Resolve parentUuid, skipping progress ancestors.
339
+ new_parent_uuid: str | None = None
340
+ parent_id: str | None = original.get("parentUuid")
341
+ while parent_id:
342
+ parent = by_uuid.get(parent_id)
343
+ if not parent:
344
+ break
345
+ if parent.get("type") != "progress":
346
+ new_parent_uuid = uuid_mapping.get(parent_id)
347
+ break
348
+ parent_id = parent.get("parentUuid")
349
+
350
+ # Only update timestamp on the last message (leaf detection on resume).
351
+ timestamp = now if i == len(writable) - 1 else original.get("timestamp", now)
352
+
353
+ # Remap logicalParentUuid (compact-boundary backpointer).
354
+ logical_parent = original.get("logicalParentUuid")
355
+ new_logical_parent = uuid_mapping.get(logical_parent) if logical_parent else logical_parent
356
+
357
+ forked = {
358
+ **original,
359
+ "uuid": new_uuid,
360
+ "parentUuid": new_parent_uuid,
361
+ "logicalParentUuid": new_logical_parent,
362
+ "sessionId": forked_session_id,
363
+ "timestamp": timestamp,
364
+ # Clear session-specific fields from the spread
365
+ "isSidechain": False,
366
+ "forkedFrom": {
367
+ "sessionId": session_id,
368
+ "messageUuid": original["uuid"],
369
+ },
370
+ }
371
+ # Remove fields that would leak state from the source session
372
+ for key in ("teamName", "agentName", "slug", "sourceToolAssistantUUID"):
373
+ forked.pop(key, None)
374
+
375
+ lines.append(json.dumps(forked, separators=(",", ":")))
376
+
377
+ # Append content-replacement entry (if any) with the fork's sessionId.
378
+ if content_replacements:
379
+ lines.append(
380
+ json.dumps(
381
+ {
382
+ "type": "content-replacement",
383
+ "sessionId": forked_session_id,
384
+ "replacements": content_replacements,
385
+ },
386
+ separators=(",", ":"),
387
+ )
388
+ )
389
+
390
+ # Derive title: explicit > original customTitle/aiTitle > first prompt.
391
+ fork_title = title.strip() if title else None
392
+ if not fork_title:
393
+ buf_len = len(content)
394
+ head = content[: min(buf_len, LITE_READ_BUF_SIZE)].decode("utf-8", errors="replace")
395
+ tail = content[max(0, buf_len - LITE_READ_BUF_SIZE) :].decode("utf-8", errors="replace")
396
+ base = (
397
+ _extract_last_json_string_field(tail, "customTitle")
398
+ or _extract_last_json_string_field(head, "customTitle")
399
+ or _extract_last_json_string_field(tail, "aiTitle")
400
+ or _extract_last_json_string_field(head, "aiTitle")
401
+ or _extract_first_prompt_from_head(head)
402
+ or "Forked session"
403
+ )
404
+ fork_title = f"{base} (fork)"
405
+
406
+ lines.append(
407
+ json.dumps(
408
+ {
409
+ "type": "custom-title",
410
+ "sessionId": forked_session_id,
411
+ "customTitle": fork_title,
412
+ },
413
+ separators=(",", ":"),
414
+ )
415
+ )
416
+
417
+ fork_path = project_dir / f"{forked_session_id}.jsonl"
418
+ fd = os.open(fork_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
419
+ try:
420
+ os.write(fd, ("\n".join(lines) + "\n").encode("utf-8"))
421
+ finally:
422
+ os.close(fd)
423
+
424
+ return ForkSessionResult(session_id=forked_session_id)
425
+
426
+
427
+ # ---------------------------------------------------------------------------
428
+ # Helpers
429
+ # ---------------------------------------------------------------------------
430
+
431
+
432
+ def _find_session_file(
433
+ session_id: str,
434
+ directory: str | None,
435
+ ) -> Path | None:
436
+ """Find the path to a session's JSONL file.
437
+
438
+ Returns the path if found, None otherwise.
439
+ """
440
+ result = _find_session_file_with_dir(session_id, directory)
441
+ return result[0] if result else None
442
+
443
+
444
+ def _find_session_file_with_dir(
445
+ session_id: str,
446
+ directory: str | None,
447
+ ) -> tuple[Path, Path] | None:
448
+ """Find a session file and its containing project directory.
449
+
450
+ Returns ``(file_path, project_dir)`` or None. The fork operation
451
+ needs the project dir to write the new file adjacent to the source.
452
+ """
453
+ file_name = f"{session_id}.jsonl"
454
+
455
+ def _try_dir(project_dir: Path) -> tuple[Path, Path] | None:
456
+ path = project_dir / file_name
457
+ try:
458
+ st = path.stat()
459
+ if st.st_size > 0:
460
+ return (path, project_dir)
461
+ except OSError:
462
+ pass
463
+ return None
464
+
465
+ if directory:
466
+ canonical = _canonicalize_path(directory)
467
+ project_dir = _find_project_dir(canonical)
468
+ if project_dir is not None:
469
+ result = _try_dir(project_dir)
470
+ if result:
471
+ return result
472
+
473
+ try:
474
+ worktree_paths = _get_worktree_paths(canonical)
475
+ except Exception:
476
+ worktree_paths = []
477
+ for wt in worktree_paths:
478
+ if wt == canonical:
479
+ continue
480
+ wt_project_dir = _find_project_dir(wt)
481
+ if wt_project_dir is not None:
482
+ result = _try_dir(wt_project_dir)
483
+ if result:
484
+ return result
485
+ return None
486
+
487
+ projects_dir = _get_projects_dir()
488
+ try:
489
+ dirents = list(projects_dir.iterdir())
490
+ except OSError:
491
+ return None
492
+ for entry in dirents:
493
+ result = _try_dir(entry)
494
+ if result:
495
+ return result
496
+ return None
497
+
498
+
499
+ _TRANSCRIPT_TYPES = frozenset({"user", "assistant", "attachment", "system", "progress"})
500
+
501
+
502
+ def _parse_fork_transcript(
503
+ content: bytes, session_id: str
504
+ ) -> tuple[list[dict[str, Any]], list[Any]]:
505
+ """Parse JSONL content into transcript entries + content-replacement records.
506
+
507
+ Only keeps entries that have a uuid and are transcript message types.
508
+ Content-replacement entries are collected for re-emission in the fork.
509
+ """
510
+ transcript: list[dict[str, Any]] = []
511
+ content_replacements: list[Any] = []
512
+
513
+ for line in content.decode("utf-8", errors="replace").splitlines():
514
+ stripped = line.strip()
515
+ if not stripped:
516
+ continue
517
+ try:
518
+ entry = anyenv.load_json(stripped, return_type=dict)
519
+ except (anyenv.JsonLoadError, ValueError):
520
+ continue
521
+ # match entry:
522
+ # case {
523
+ # "type": "user" | "assistant" | "attachment" | "system" | "progress" as typ,
524
+ # "uuid": str(id_),
525
+ # }:
526
+ # pass
527
+ entry_type = entry.get("type")
528
+ if entry_type in _TRANSCRIPT_TYPES and isinstance(entry.get("uuid"), str):
529
+ transcript.append(entry)
530
+ elif (
531
+ entry_type == "content-replacement"
532
+ and entry.get("sessionId") == session_id
533
+ and isinstance(entry.get("replacements"), list)
534
+ ):
535
+ content_replacements.extend(entry["replacements"])
536
+
537
+ return transcript, content_replacements
538
+
539
+
540
+ def _append_to_session(session_id: str, data: str, directory: str | None) -> None:
541
+ """Append data to an existing session file.
542
+
543
+ Searches candidate paths and tries the append directly — no existence
544
+ check. Uses O_WRONLY | O_APPEND (without O_CREAT) so the open fails with
545
+ ENOENT for missing files, avoiding TOCTOU.
546
+ """
547
+ file_name = f"{session_id}.jsonl"
548
+
549
+ if directory:
550
+ canonical = _canonicalize_path(directory)
551
+
552
+ # Try the exact/prefix-matched project directory first.
553
+ project_dir = _find_project_dir(canonical)
554
+ if project_dir is not None and _try_append(project_dir / file_name, data):
555
+ return
556
+
557
+ # Worktree fallback — matches list_sessions/get_session_messages.
558
+ # 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:
564
+ if wt == canonical:
565
+ continue # already tried above
566
+ wt_project_dir = _find_project_dir(wt)
567
+ if wt_project_dir is not None and _try_append(wt_project_dir / file_name, data):
568
+ return
569
+
570
+ raise FileNotFoundError(
571
+ f"Session {session_id} not found in project directory for {directory}"
572
+ )
573
+
574
+ # No directory — search all project directories by trying each directly.
575
+ projects_dir = _get_projects_dir()
576
+ try:
577
+ dirents = list(projects_dir.iterdir())
578
+ except OSError as e:
579
+ raise FileNotFoundError(f"Session {session_id} not found (no projects directory)") from e
580
+ for entry in dirents:
581
+ if _try_append(entry / file_name, data):
582
+ return
583
+ raise FileNotFoundError(f"Session {session_id} not found in any project directory")
584
+
585
+
586
+ def _try_append(path: Path, data: str) -> bool:
587
+ """Try appending to a path.
588
+
589
+ Opens with O_WRONLY | O_APPEND (no O_CREAT), so the open fails with
590
+ ENOENT if the file does not exist — no separate existence check.
591
+
592
+ Returns ``True`` on successful write, ``False`` if the file does not
593
+ exist (ENOENT/ENOTDIR) or is 0-byte. A 0-byte ``.jsonl`` is a "session
594
+ not here, keep searching" signal that readers (``_read_session_lite``)
595
+ already honor; without this guard the search would stop at an empty stub
596
+ in one project dir while the real file lives in a worktree. Re-raises all
597
+ other errors (ENOSPC, EACCES, EIO, etc.) so real write failures surface.
598
+
599
+ O_APPEND semantics: Python's ``os.open`` with ``os.O_APPEND`` maps to the
600
+ kernel's append mode on all platforms. On POSIX, O_APPEND makes the kernel
601
+ atomically seek-to-EOF on every write (race-free). On Windows, CPython's
602
+ ``os.open`` translates O_APPEND to ``FILE_APPEND_DATA`` (also atomic).
603
+ CPython handles this correctly on all platforms, so no explicit-position
604
+ fallback is needed.
605
+ """
606
+ try:
607
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND)
608
+ except OSError as e:
609
+ if e.errno in (errno.ENOENT, errno.ENOTDIR):
610
+ return False
611
+ raise
612
+ try:
613
+ stat = os.fstat(fd)
614
+ if stat.st_size == 0:
615
+ return False
616
+ os.write(fd, data.encode("utf-8"))
617
+ return True
618
+ finally:
619
+ os.close(fd)
620
+
621
+
622
+ # ---------------------------------------------------------------------------
623
+ # Unicode sanitization
624
+ # ---------------------------------------------------------------------------
625
+
626
+ # Explicit ranges for dangerous Unicode characters. Python's regex supports
627
+ # Unicode categories via \p{} only in the third-party `regex` module, so we
628
+ # use explicit ranges here (matching the TS fallback paths).
629
+ _UNICODE_STRIP_RE = re.compile(
630
+ "["
631
+ "\u200b-\u200f" # Zero-width spaces, LTR/RTL marks
632
+ "\u202a-\u202e" # Directional formatting characters
633
+ "\u2066-\u2069" # Directional isolates
634
+ "\ufeff" # Byte order mark
635
+ "\ue000-\uf8ff" # Basic Multilingual Plane private use
636
+ "]"
637
+ )
638
+
639
+ # Format characters (Cf category) — the ones most commonly abused for
640
+ # injection. We check this per-character since Python's re module doesn't
641
+ # support \p{Cf} without the third-party regex module.
642
+ _FORMAT_CATEGORIES = frozenset({"Cf", "Co", "Cn"})
643
+
644
+
645
+ def _sanitize_unicode(value: str) -> str:
646
+ """Sanitize a string by removing dangerous Unicode characters.
647
+
648
+ Iteratively applies NFKC
649
+ normalization and strips format/private-use/unassigned characters until
650
+ no more changes occur (max 10 iterations).
651
+ """
652
+ current = value
653
+ for _ in range(10):
654
+ previous = current
655
+ # Apply NFKC normalization to handle composed character sequences
656
+ current = unicodedata.normalize("NFKC", current)
657
+ # Strip Cf (format), Co (private use), Cn (unassigned) categories
658
+ current = "".join(c for c in current if unicodedata.category(c) not in _FORMAT_CATEGORIES)
659
+ # Explicit ranges (redundant with category check but matches TS)
660
+ current = _UNICODE_STRIP_RE.sub("", current)
661
+ if current == previous:
662
+ break
663
+ return current