-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathmessage_parser.py
More file actions
294 lines (277 loc) · 12.1 KB
/
message_parser.py
File metadata and controls
294 lines (277 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""Message parser for Claude Code SDK responses."""
import logging
from typing import Any
from .._errors import MessageParseError
from ..types import (
AssistantMessage,
ContentBlock,
Message,
MirrorErrorMessage,
RateLimitEvent,
RateLimitInfo,
ResultMessage,
ServerToolResultBlock,
ServerToolUseBlock,
StreamEvent,
SystemMessage,
TaskNotificationMessage,
TaskProgressMessage,
TaskStartedMessage,
TextBlock,
ThinkingBlock,
ToolResultBlock,
ToolUseBlock,
UserMessage,
)
logger = logging.getLogger(__name__)
def parse_message(data: dict[str, Any]) -> Message | None:
"""
Parse message from CLI output into typed Message objects.
Args:
data: Raw message dictionary from CLI output
Returns:
Parsed Message object
Raises:
MessageParseError: If parsing fails or message type is unrecognized
"""
if not isinstance(data, dict):
raise MessageParseError(
f"Invalid message data type (expected dict, got {type(data).__name__})",
data,
)
message_type = data.get("type")
if not message_type:
raise MessageParseError("Message missing 'type' field", data)
match message_type:
case "user":
try:
parent_tool_use_id = data.get("parent_tool_use_id")
tool_use_result = data.get("tool_use_result")
uuid = data.get("uuid")
if isinstance(data["message"]["content"], list):
user_content_blocks: list[ContentBlock] = []
for block in data["message"]["content"]:
match block["type"]:
case "text":
user_content_blocks.append(
TextBlock(text=block["text"])
)
case "tool_use":
user_content_blocks.append(
ToolUseBlock(
id=block["id"],
name=block["name"],
input=block["input"],
)
)
case "tool_result":
user_content_blocks.append(
ToolResultBlock(
tool_use_id=block["tool_use_id"],
content=block.get("content"),
is_error=block.get("is_error"),
)
)
return UserMessage(
content=user_content_blocks,
uuid=uuid,
timestamp=data.get("timestamp"),
parent_tool_use_id=parent_tool_use_id,
tool_use_result=tool_use_result,
)
return UserMessage(
content=data["message"]["content"],
uuid=uuid,
timestamp=data.get("timestamp"),
parent_tool_use_id=parent_tool_use_id,
tool_use_result=tool_use_result,
)
except KeyError as e:
raise MessageParseError(
f"Missing required field in user message: {e}", data
) from e
case "assistant":
try:
content_blocks: list[ContentBlock] = []
for block in data["message"]["content"]:
match block["type"]:
case "text":
content_blocks.append(TextBlock(text=block["text"]))
case "thinking":
content_blocks.append(
ThinkingBlock(
thinking=block["thinking"],
signature=block["signature"],
)
)
case "tool_use":
content_blocks.append(
ToolUseBlock(
id=block["id"],
name=block["name"],
input=block["input"],
)
)
case "tool_result":
content_blocks.append(
ToolResultBlock(
tool_use_id=block["tool_use_id"],
content=block.get("content"),
is_error=block.get("is_error"),
)
)
case "server_tool_use":
content_blocks.append(
ServerToolUseBlock(
id=block["id"],
name=block["name"],
input=block["input"],
)
)
case "advisor_tool_result":
content_blocks.append(
ServerToolResultBlock(
tool_use_id=block["tool_use_id"],
content=block["content"],
)
)
return AssistantMessage(
content=content_blocks,
model=data["message"]["model"],
parent_tool_use_id=data.get("parent_tool_use_id"),
error=data.get("error"),
usage=data["message"].get("usage"),
message_id=data["message"].get("id"),
stop_reason=data["message"].get("stop_reason"),
session_id=data.get("session_id"),
uuid=data.get("uuid"),
timestamp=data.get("timestamp"),
)
except KeyError as e:
raise MessageParseError(
f"Missing required field in assistant message: {e}", data
) from e
case "system":
try:
subtype = data["subtype"]
match subtype:
case "task_started":
return TaskStartedMessage(
subtype=subtype,
data=data,
task_id=data["task_id"],
description=data["description"],
uuid=data["uuid"],
session_id=data["session_id"],
tool_use_id=data.get("tool_use_id"),
task_type=data.get("task_type"),
timestamp=data.get("timestamp"),
)
case "task_progress":
return TaskProgressMessage(
subtype=subtype,
data=data,
task_id=data["task_id"],
description=data["description"],
usage=data["usage"],
uuid=data["uuid"],
session_id=data["session_id"],
tool_use_id=data.get("tool_use_id"),
last_tool_name=data.get("last_tool_name"),
timestamp=data.get("timestamp"),
)
case "task_notification":
return TaskNotificationMessage(
subtype=subtype,
data=data,
task_id=data["task_id"],
status=data["status"],
output_file=data["output_file"],
summary=data["summary"],
uuid=data["uuid"],
session_id=data["session_id"],
tool_use_id=data.get("tool_use_id"),
usage=data.get("usage"),
timestamp=data.get("timestamp"),
)
case "mirror_error":
# SDK-synthesized via report_mirror_error — never emitted by the CLI subprocess.
return MirrorErrorMessage(
subtype=subtype,
data=data,
key=data.get("key"),
error=data.get("error", ""),
timestamp=data.get("timestamp"),
)
case _:
return SystemMessage(
subtype=subtype,
data=data,
timestamp=data.get("timestamp"),
)
except KeyError as e:
raise MessageParseError(
f"Missing required field in system message: {e}", data
) from e
case "result":
try:
return ResultMessage(
subtype=data["subtype"],
duration_ms=data["duration_ms"],
duration_api_ms=data["duration_api_ms"],
is_error=data["is_error"],
num_turns=data["num_turns"],
session_id=data["session_id"],
stop_reason=data.get("stop_reason"),
total_cost_usd=data.get("total_cost_usd"),
usage=data.get("usage"),
result=data.get("result"),
structured_output=data.get("structured_output"),
model_usage=data.get("modelUsage"),
permission_denials=data.get("permission_denials"),
errors=data.get("errors"),
uuid=data.get("uuid"),
timestamp=data.get("timestamp"),
)
except KeyError as e:
raise MessageParseError(
f"Missing required field in result message: {e}", data
) from e
case "stream_event":
try:
return StreamEvent(
uuid=data["uuid"],
session_id=data["session_id"],
event=data["event"],
parent_tool_use_id=data.get("parent_tool_use_id"),
)
except KeyError as e:
raise MessageParseError(
f"Missing required field in stream_event message: {e}", data
) from e
case "rate_limit_event":
try:
info = data["rate_limit_info"]
return RateLimitEvent(
rate_limit_info=RateLimitInfo(
status=info["status"],
resets_at=info.get("resetsAt"),
rate_limit_type=info.get("rateLimitType"),
utilization=info.get("utilization"),
overage_status=info.get("overageStatus"),
overage_resets_at=info.get("overageResetsAt"),
overage_disabled_reason=info.get("overageDisabledReason"),
raw=info,
),
uuid=data["uuid"],
session_id=data["session_id"],
)
except KeyError as e:
raise MessageParseError(
f"Missing required field in rate_limit_event message: {e}", data
) from e
case _:
# Forward-compatible: skip unrecognized message types so newer
# CLI versions don't crash older SDK versions.
logger.debug("Skipping unknown message type: %s", message_type)
return None