Repository navigation
Expand file tree
/
Copy pathmodels.py
More file actions
2431 lines (1835 loc) · 81.2 KB
/
Copy pathmodels.py
File metadata and controls
2431 lines (1835 loc) · 81.2 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Pydantic models for Claude Code transcript JSON structures."""
import json
import re
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, ClassVar, Union, Optional, Literal, cast
from pydantic import BaseModel, Field
from .json_depth import exceeds_depth
class MessageType(str, Enum):
"""Primary message type classification.
This enum covers both JSONL entry types and rendering types.
Using str as base class maintains backward compatibility with string comparisons.
JSONL Entry Types (from transcript files):
- USER, ASSISTANT, SYSTEM, SUMMARY, QUEUE_OPERATION
Rendering Types (derived during processing):
- TOOL_USE, TOOL_RESULT, THINKING, IMAGE
- BASH_INPUT, BASH_OUTPUT
- SESSION_HEADER, UNKNOWN
"""
# JSONL entry types
USER = "user"
ASSISTANT = "assistant"
SYSTEM = "system"
SUMMARY = "summary"
QUEUE_OPERATION = "queue-operation"
AI_TITLE = "ai-title"
# Rendering/display types (derived from content)
TOOL_USE = "tool_use"
TOOL_RESULT = "tool_result"
THINKING = "thinking"
IMAGE = "image"
BASH_INPUT = "bash-input"
BASH_OUTPUT = "bash-output"
SESSION_HEADER = "session-header"
UNKNOWN = "unknown"
# System subtypes (for css_class)
SYSTEM_INFO = "system-info"
SYSTEM_WARNING = "system-warning"
SYSTEM_ERROR = "system-error"
class RenderingDepth(str, Enum):
"""How deep into the message hierarchy to render (#159).
Depths name the message-hierarchy node the output stops at, ordered
most-content-first (deepest to shallowest):
hook > tool > agent > assistant > user > session.
The ``--depth`` CLI option uses these names directly. The deprecated
``--detail`` option (removed in 2.0) maps its legacy verbosity names
onto them via ``DETAIL_ALIASES``. ``session`` is depth-only — it has
no ``--detail`` spelling.
Enum values ARE the ``--depth`` names, so they double as the filename
suffix (see ``utils.variant_suffix``).
"""
HOOK = "hook" # Everything, incl. hooks + system notices (--detail full)
TOOL = "tool" # Detailed but cleaned, no system/hook noise (--detail high; DEFAULT)
AGENT = "agent" # Interaction-focused + key tool signals (--detail low)
ASSISTANT = "assistant" # User + assistant messages only (--detail minimal)
USER = "user" # User prompts + steering only (--detail user-only)
SESSION = "session" # Session structure only: headers/nav (depth-only)
def includes(self, threshold: "RenderingDepth") -> bool:
"""Return True iff this depth is deep enough to show content whose
``depth_visibility`` is declared at ``threshold``.
Monotone: ``HOOK.includes(X)`` is True for every ``X``;
``SESSION.includes(X)`` is True only for ``SESSION`` itself.
"""
return _DEPTH_ORDER[self] <= _DEPTH_ORDER[threshold]
# Depth ordering: lower index = deeper (more content). ``RenderingDepth.includes``
# (and ``MessageContent.visible_at``) treats a depth as "deep enough" iff
# ``order[current] <= order[threshold]``.
_DEPTH_ORDER: dict[RenderingDepth, int] = {
RenderingDepth.HOOK: 0,
RenderingDepth.TOOL: 1,
RenderingDepth.AGENT: 2,
RenderingDepth.ASSISTANT: 3,
RenderingDepth.USER: 4,
RenderingDepth.SESSION: 5,
}
# Guard against drift: if a new RenderingDepth value is added without an
# entry here, ``includes`` would raise KeyError silently on first use.
# Fail loudly at import time instead. Uses ``if ... raise`` rather than
# ``assert`` so the check survives ``python -O`` / ``PYTHONOPTIMIZE``.
if set(_DEPTH_ORDER.keys()) != set(RenderingDepth):
raise RuntimeError(
f"_DEPTH_ORDER missing entries for: {set(RenderingDepth) - set(_DEPTH_ORDER.keys())}"
)
# The default output depth (#159): ``--depth tool`` — detailed but cleaned
# of system/hook noise. A bare invocation (no --depth, no --detail) and the
# no-suffix output filename both mean this depth.
DEFAULT_DEPTH: RenderingDepth = RenderingDepth.TOOL
# Deprecated ``--detail`` value → ``RenderingDepth`` (#159). ``--detail`` is
# removed in 2.0; until then its legacy verbosity names map onto the depth
# scale. ``session`` has no ``--detail`` spelling.
DETAIL_ALIASES: dict[str, RenderingDepth] = {
"full": RenderingDepth.HOOK,
"high": RenderingDepth.TOOL,
"low": RenderingDepth.AGENT,
"minimal": RenderingDepth.ASSISTANT,
"user-only": RenderingDepth.USER,
}
# =============================================================================
# JSONL Content Models (Pydantic)
# =============================================================================
# Low-level content types parsed from JSONL transcript entries.
# These are defined first as they're the "input" types from transcript files.
class TextContent(BaseModel):
"""Text content block within a message content array."""
type: Literal["text"]
text: str
class ImageSource(BaseModel):
"""Base64-encoded image source data."""
type: Literal["base64"]
media_type: str
data: str
class ImageContent(BaseModel):
"""Image content.
This represents an image within a content array, not a standalone message.
Images are always part of UserTextMessage.items or AssistantTextMessage.items.
"""
type: Literal["image"]
source: ImageSource
class UsageInfo(BaseModel):
"""Token usage information for tracking API consumption."""
input_tokens: Optional[int] = None
cache_creation_input_tokens: Optional[int] = None
cache_read_input_tokens: Optional[int] = None
output_tokens: Optional[int] = None
service_tier: Optional[str] = None
server_tool_use: Optional[dict[str, Any]] = None
class ToolUseContent(BaseModel):
type: Literal["tool_use"]
id: str
name: str
input: dict[str, Any]
class ToolResultContent(BaseModel):
type: Literal["tool_result"]
tool_use_id: str
content: Union[str, list[dict[str, Any]]]
is_error: Optional[bool] = None
agentId: Optional[str] = None # Reference to agent file for sub-agent messages
class ThinkingContent(BaseModel):
type: Literal["thinking"]
thinking: str
signature: Optional[str] = None
# Content item types that appear in message content arrays
ContentItem = Union[
TextContent,
ToolUseContent,
ToolResultContent,
ThinkingContent,
ImageContent,
]
class UserMessageModel(BaseModel):
role: Literal["user"]
content: list[ContentItem]
usage: Optional["UsageInfo"] = (
None # For type compatibility with AssistantMessageModel
)
class AssistantMessageModel(BaseModel):
"""Assistant message model."""
id: str
type: Literal["message"]
role: Literal["assistant"]
model: str
content: list[ContentItem]
stop_reason: Optional[str] = None
stop_sequence: Optional[str] = None
usage: Optional[UsageInfo] = None
# Tool result type - flexible to accept various result formats from JSONL
# The specific parsing/formatting happens in tool_formatters.py using
# ReadOutput, EditOutput, etc. (see Tool Output Content Models section)
ToolUseResult = Union[
str,
list[Any], # Covers list[TodoWriteItem], list[ContentItem], etc.
dict[str, Any], # Covers structured results
]
class BaseTranscriptEntry(BaseModel):
parentUuid: Optional[str]
isSidechain: bool
userType: str
cwd: str
sessionId: str
version: str
uuid: str
timestamp: str
isMeta: Optional[bool] = None
agentId: Optional[str] = None # Agent ID for sidechain messages
gitBranch: Optional[str] = None # Git branch name when available
teamName: Optional[str] = None # Active team name (teammates feature)
# Synthetic (set by the loader, never by Claude Code): the id of the
# sub-agent spawned by this entry's Agent/Task tool_use or tool_result,
# resolved from ``subagents/agent-<id>.meta.json`` (``toolUseId``) or the
# trunk's ``toolUseResult.agentId``. Distinct from ``agentId``, which is
# *membership* (whose transcript this entry belongs to) — inside an agent
# transcript the two necessarily differ, which is what makes nested
# agent→agent spawns (issue #213) linkable.
#
# A single field suffices because Claude Code streams one content block
# per assistant entry (parallel spawns arrive as separate entries) and
# tool_results anchor 1:1 on their own entries. The degenerate
# several-resultless-spawns-in-one-entry shape — unobserved in real
# transcripts — degrades to the relocation tail-append, never to data
# loss (see ``converter._apply_subagent_meta_links``).
spawnedAgentId: Optional[str] = None
class UserTranscriptEntry(BaseTranscriptEntry):
type: Literal["user"]
message: UserMessageModel
toolUseResult: Optional[ToolUseResult] = None
agentId: Optional[str] = None # From toolUseResult when present
# Paste ids for the image blocks in ``message.content``, in block order:
# the ``[Image #N]`` placeholder in the text refers to the block at
# ``imagePasteIds.index(N)``. N is a paste counter, NOT a position — it
# resets when the CLI restarts inside a session that outlives it, and it
# increments on delete-and-repaste, so the same N can name different
# images within one session and nothing may be keyed at session scope.
# Old transcripts do not carry it (see _image_reference_mapping for what
# is then left to go on, and dev-docs/messages.md for the sampling).
#
# Deliberately untyped: a malformed value has to reach the resolver to be
# reported, because a ValidationError here would drop the whole entry
# (the loader skips any line whose model validation raises).
imagePasteIds: Optional[Any] = None
# Present on isMeta=True entries produced by a Skill tool invocation —
# carries the id of the originating tool_use so the renderer can fold
# the skill body into that tool_use block. See issue #93.
sourceToolUseID: Optional[str] = None
class AssistantTranscriptEntry(BaseTranscriptEntry):
type: Literal["assistant"]
message: AssistantMessageModel
requestId: Optional[str] = None
class SummaryTranscriptEntry(BaseModel):
type: Literal["summary"]
summary: str
leafUuid: str
cwd: Optional[str] = None
sessionId: None = None # Summaries don't have a sessionId
class AiTitleTranscriptEntry(BaseModel):
"""AI-generated session title.
Claude Code emits these as session-level metadata (no uuid, no parent
chain). Multiple entries may be written per session as the title is
refined; the last one wins.
"""
type: Literal["ai-title"]
aiTitle: str
sessionId: str
class SystemTranscriptEntry(BaseTranscriptEntry):
"""System messages like warnings, notifications, hook summaries, etc."""
type: Literal["system"]
content: Optional[str] = None
subtype: Optional[str] = None # e.g., "stop_hook_summary"
level: Optional[str] = None # e.g., "warning", "info", "error"
# Hook summary fields (for subtype="stop_hook_summary")
hasOutput: Optional[bool] = None
hookErrors: Optional[list[str]] = None
hookInfos: Optional[list[dict[str, Any]]] = None
preventedContinuation: Optional[bool] = None
# Compact boundary fields (for subtype="compact_boundary"); primarily
# `preTokens`, `trigger`, `postTokens`, `durationMs`. Read at factory
# time into SystemMessage.compact_pre_tokens / compact_trigger.
compactMetadata: Optional[dict[str, Any]] = None
# A compact_boundary starts a fresh chain (parentUuid is null); this names
# the message it logically continues, which may sit on a rewind branch.
logicalParentUuid: Optional[str] = None
class QueueOperationTranscriptEntry(BaseModel):
"""Queue operations (enqueue/dequeue/remove) for message queueing tracking.
enqueue/dequeue are internal operations that track when messages are queued and dequeued.
They are parsed but not rendered, as the content duplicates actual user messages.
'remove' operations are out-of-band user inputs made visible to the agent while working
for "steering" purposes. These should be rendered as user messages with a 'steering' CSS class.
Content can be a list of ContentItems or a simple string (for 'remove' operations).
"""
type: Literal["queue-operation"]
operation: Literal["enqueue", "dequeue", "remove", "popAll"]
timestamp: str
sessionId: str
content: Optional[Union[list[ContentItem], str]] = (
None # List for enqueue, str for remove/popAll
)
class PassthroughTranscriptEntry(BaseModel):
"""Structural-only entry for DAG chain continuity.
Captures entries that have uuid/parentUuid and participate in the
DAG chain but are not rendered (e.g. ``progress`` async-hook
callbacks, ``agent-setting``, ``pr-link``, ``ai-title``). Without
these, messages whose parentUuid points to a dropped entry would
become false roots in the DAG.
Note: ``attachment`` entries (hook callbacks, deferred tool deltas,
etc.) are now their own typed ``AttachmentTranscriptEntry`` so the
hook payload is available for full-detail rendering. They keep the
same structural-DAG semantics — see ``_StructuralEntry`` in
``dag.py``.
"""
uuid: str
parentUuid: Optional[str] = None
sessionId: str
timestamp: str
type: Optional[str] = None # Original type (e.g. "progress")
isSidechain: bool = False
agentId: Optional[str] = None
class AttachmentTranscriptEntry(BaseTranscriptEntry):
"""Out-of-band ``type: "attachment"`` entry produced by the harness.
Claude Code emits ``attachment`` entries for hook callbacks
(``hook_success``, ``hook_blocking_error``, …), deferred-tool
deltas, queued commands, file references, todo/task reminders, and
similar harness-side metadata. They sit in the JSONL chain — they
have ``uuid``/``parentUuid`` and participate in the DAG — but are
not part of the user/assistant conversation.
The ``attachment`` payload is a heterogeneous dict whose shape
depends on ``attachment.type``. Hook flavours
(``hook_success``, ``hook_additional_context``, ``hook_blocking_error``,
``hook_non_blocking_error``) are surfaced at full-detail by the
``HookAttachmentMessage`` factory; other flavours stay structural
(visible in the DAG, dropped from the rendered output) until they
grow a dedicated factory branch.
Anchoring: the example in issue #128 confirmed ``parentUuid`` is
the right anchor (a ``UserPromptSubmit`` hook attachment carried a
``toolUseID`` that matched nothing in the project — the
``parentUuid`` did). So this class follows the same parent edge as
every other transcript entry.
"""
type: Literal["attachment"]
attachment: dict[str, Any] = Field(default_factory=dict)
# Most real-world attachments carry the full BaseTranscriptEntry
# context (userType/cwd/version), but minimal/synthetic fixtures
# (and conceivably future harness shapes) may omit them. Default
# them so validation is forgiving — the rendering layer treats
# attachments as structural noise anyway and these fields are
# only consulted for ``MessageMeta`` plumbing.
userType: str = "external" # pyright: ignore[reportIncompatibleVariableOverride]
cwd: str = "" # pyright: ignore[reportIncompatibleVariableOverride]
version: str = "" # pyright: ignore[reportIncompatibleVariableOverride]
TranscriptEntry = Union[
UserTranscriptEntry,
AssistantTranscriptEntry,
SummaryTranscriptEntry,
AiTitleTranscriptEntry,
SystemTranscriptEntry,
QueueOperationTranscriptEntry,
AttachmentTranscriptEntry,
PassthroughTranscriptEntry,
]
# =============================================================================
# Message Metadata
# =============================================================================
# Common metadata fields extracted from transcript entries.
@dataclass
class MessageMeta:
"""Common metadata extracted from transcript entries.
These fields are shared across all message types and are used to create
the TemplateMessage wrapper for rendering.
Note: formatted_timestamp is computed at render time, not stored here.
"""
# Identity fields
session_id: str
timestamp: str # Raw ISO timestamp
uuid: str
parent_uuid: Optional[str] = None
# Context fields
is_sidechain: bool = False
is_meta: bool = False # User slash command (isMeta=True in transcript)
source_tool_use_id: Optional[str] = (
None # Skill pairing (see UserTranscriptEntry.sourceToolUseID)
)
agent_id: Optional[str] = None
# Sub-agent spawned by this entry's Agent/Task tool call (issue #213);
# see BaseTranscriptEntry.spawnedAgentId for the membership/reference
# distinction.
spawned_agent_id: Optional[str] = None
cwd: str = ""
git_branch: Optional[str] = None
team_name: Optional[str] = None # Active team name (teammates feature)
# The model id the assistant entry ran on (AssistantMessageModel.model),
# e.g. ``claude-opus-4-8``. Only assistant entries carry it; None elsewhere.
# Surfaced on sub-agent message headers so a reader can see which model a
# spawned agent used (issue #246).
model: Optional[str] = None
@classmethod
def empty(cls, uuid: str = "") -> "MessageMeta":
"""Create a placeholder MessageMeta with empty/default values.
Useful for cases where full metadata isn't available at creation time
(e.g., SummaryTranscriptEntry where session_id is matched later).
"""
return cls(session_id="", timestamp="", uuid=uuid)
# =============================================================================
# Message Content Models
# =============================================================================
# Structured content models for format-neutral message representation.
# These replace the direct HTML generation in renderer.py, allowing different
# renderers (HTML, text, etc.) to format the content appropriately.
@dataclass
class MessageContent:
"""Base class for structured message content.
Subclasses represent specific content types that renderers can format
appropriately for their output format.
The `meta` field is required and first positional, ensuring all message
content always has associated metadata. Use MessageMeta.empty() when
full metadata isn't available at creation time.
Note: Render-time relationship data (pairing, hierarchy, children) is stored
on TemplateMessage, not here. MessageContent is pure transcript data,
except for message_index which links back to TemplateMessage for render-time
lookups (e.g., accessing paired messages).
"""
meta: MessageMeta
# Set by RenderingContext.register() to enable content→TemplateMessage lookup
# Using init=False to avoid dataclass inheritance issues with required fields
# compare=False: the index is assigned per render tree, and the fragment
# store compares two trees' contents for the same source entry to decide
# whether a cached fragment may be reused — a per-tree field must not
# defeat that comparison (the contents ARE the same message).
message_index: Optional[int] = field(
default=None, init=False, repr=False, compare=False
)
# Identity of the source (TranscriptEntry, part) this content was built
# from: ``(id(entry), part_ordinal)``. Stamped by the pass-2 render loop
# for entry-derived content only — synthesized content (session/branch
# headers, grafted sidechannel nodes, ghost placeholders) stays None and
# is always formatted fresh. Valid only while the conversion's master
# message list keeps every entry alive (an ``id()`` can be reused after
# its object is freed), which is why the fragment store that consumes it
# is scoped to a single conversion. NOT a uuid: transcript uuids collide
# across resumed/forked sessions (see work/render-format-once.md § 4.1).
# compare=False for the same reason as message_index.
fragment_key: Optional[tuple[int, int]] = field(
default=None, init=False, repr=False, compare=False
)
@property
def message_type(self) -> str:
"""Return the message type identifier for this content.
Subclasses MUST override this to return their specific type.
This is used for CSS classes, filtering, and type-based rendering.
"""
raise NotImplementedError("Subclasses must implement message_type property")
@property
def has_markdown(self) -> bool:
"""Whether this content should be rendered as markdown.
Subclasses that contain markdown content should override to return True.
"""
return False
def visible_at(self, depth: RenderingDepth) -> bool:
"""Return True iff this content is visible at ``depth``.
Resolution: each subclass MAY declare a class-level
``depth_visibility: ClassVar[RenderingDepth]`` that names the LEAST
verbose level at which it should still render. The predicate is
monotone-down — a class declared at ``TOOL`` is visible at
``HOOK`` and ``TOOL`` and dropped at ``AGENT`` and below
(see :meth:`RenderingDepth.includes`).
Classes without a declared threshold are always visible — useful
for built-ins like ``UserTextMessage`` that have no level-based
filtering rule. Plugin subclasses inherit the threshold from
their base via normal ClassVar inheritance unless they declare
their own (documented contract — see ``dev-docs/plugins.md``).
"""
threshold = getattr(type(self), "depth_visibility", None)
if threshold is None:
return True
return depth.includes(threshold)
@dataclass
class SystemMessage(MessageContent):
"""System message with level indicator.
Used for info, warning, and error system messages.
"""
# System info/warning/error noise — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
level: str # "info", "warning", "error"
text: str # Raw text content (may contain ANSI codes)
# Populated only for subtype="compact_boundary" entries: the token
# count before compaction and what triggered it ("manual"/"auto").
# Surfaced in the nav landmark label for /compact points.
compact_pre_tokens: Optional[int] = None
compact_trigger: Optional[str] = None
# The boundary's ``logicalParentUuid``: it has no ``parentUuid``, so this
# names the message it continues. Display-only (the debug uuid line);
# kept out of ``meta.parent_uuid``, which drives lookup and pairing.
compact_logical_parent_uuid: Optional[str] = None
@property
def message_type(self) -> str:
return "system"
@dataclass
class HookInfo:
"""Information about a single hook execution."""
command: str
# Could add more fields like exit_code, duration, etc.
@dataclass
class HookSummaryMessage(MessageContent):
"""Hook execution summary.
Used for subtype="stop_hook_summary" system messages.
"""
# Hook noise — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
has_output: bool
hook_errors: list[str] # Error messages from hooks
hook_infos: list[HookInfo] # Info about each hook executed
@property
def message_type(self) -> str:
return "system"
@dataclass
class AwaySummaryMessage(MessageContent):
"""Recap of recent activity, emitted by Claude Code's "away_summary" feature.
Used for system entries with subtype="away_summary" — narrative prose
summarising what the assistant was doing, intended to surface when the
user comes back to a session. Distinct from HookSummaryMessage (tool noise)
and the level-bearing SystemMessage (info/warning/error).
"""
# Recaps are a high-level summary of activity, so they stay visible at
# EVERY depth level — including user-only, where "user said this, agent
# did that (just the recap)" is exactly the wanted view (#179). Declared at
# the least-verbose threshold (USER) via the class-attribute
# depth-visibility mechanism. Suppress them explicitly with ``--no-recaps``
# (handled in ``_ghost_template_by_depth``), not by lowering this.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.USER
text: str # Recap prose; may contain light markdown.
@property
def message_type(self) -> str:
return "system"
@property
def has_markdown(self) -> bool:
return True
@dataclass
class HookAttachmentMessage(MessageContent):
"""Hook callback recorded as a ``type: "attachment"`` entry (issue #128).
Distinct from ``HookSummaryMessage`` (which represents the
``stop_hook_summary`` *system* entry — a roll-up of the hooks that
ran for a single Stop event). This one represents an individual
hook invocation captured by the harness as an attachment, with
full payload (command, exit code, stdout/stderr, duration). Visible
only at ``RenderingDepth.HOOK``; dropped at TOOL and below alongside
other hook noise (see ``depth_visibility`` below).
``kind`` distinguishes the attachment flavour:
- ``success`` (``hook_success``): hook ran cleanly, payload is
command + stdout/stderr + exitCode + durationMs.
- ``additional_context`` (``hook_additional_context``):
``UserPromptSubmit`` / ``SessionStart`` hook injected extra
prompt context. Payload is a list of strings in ``content``.
- ``blocking_error`` (``hook_blocking_error``): hook prevented
the tool call. Payload is a nested ``blockingError`` object.
- ``non_blocking_error`` (``hook_non_blocking_error``): hook
reported an error but didn't block. Same shape as ``success``
but with non-zero ``exitCode``.
"""
# Hook attachment noise — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
kind: str # success / additional_context / blocking_error / non_blocking_error
hook_event: str = "" # PostToolUse / UserPromptSubmit / Stop / SessionStart / ...
hook_name: str = "" # e.g. "PostToolUse:TaskUpdate"
tool_use_id: Optional[str] = None
command: Optional[str] = None
exit_code: Optional[int] = None
duration_ms: Optional[int] = None
content: str = "" # Free-form hook content (joined if list)
stdout: str = ""
stderr: str = ""
blocking_error: Optional[str] = None # blockingError.blockingError text
@property
def message_type(self) -> str:
return "system"
# =============================================================================
# User Message Content Models
# =============================================================================
# Structured content models for user message variants.
# These classify user text based on flags and tag patterns.
@dataclass
class SlashCommandMessage(MessageContent):
"""Content for slash command invocations (e.g., /context, /model).
These are user messages containing command-name, command-args, and
command-contents tags parsed from the text.
"""
# Slash-command framing — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
command_name: str
command_args: str
command_contents: str
@property
def message_type(self) -> str:
return "user"
@dataclass
class CommandOutputMessage(MessageContent):
"""Content for local command output (e.g., output from /context).
These are user messages containing local-command-stdout tags.
"""
# Local-command output — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
stdout: str
is_markdown: bool # True if content appears to be markdown
@property
def message_type(self) -> str:
return "user"
@dataclass
class BashInputMessage(MessageContent):
"""Content for inline bash commands in user messages.
These are user messages containing bash-input tags.
"""
# Inline bash — kept through TOOL, dropped at AGENT and below.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.TOOL
command: str
@property
def message_type(self) -> str:
return "bash-input"
@dataclass
class BashOutputMessage(MessageContent):
"""Content for bash command output.
These are user messages containing bash-stdout and/or bash-stderr tags.
"""
# Inline bash output — kept through TOOL, dropped at AGENT and below.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.TOOL
stdout: Optional[str] = None # Raw stdout content (may contain ANSI codes)
stderr: Optional[str] = None # Raw stderr content (may contain ANSI codes)
@property
def message_type(self) -> str:
return "bash-output"
# Note: ToolResultMessage and ToolUseMessage are defined in the
# "Tool Message Models" section (before Tool Input Models).
@dataclass
class CompactedSummaryMessage(MessageContent):
"""Content for compacted session summaries.
These are user messages that contain previous conversation context
in a compacted format when sessions run out of context.
Parsed by parse_compacted_summary() in parser.py, formatted by
format_compacted_summary_content() in html/user_formatters.py.
"""
# /compact framing — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
summary_text: str
@property
def message_type(self) -> str:
return "user"
@property
def has_markdown(self) -> bool:
return True
@dataclass
class UserMemoryMessage(MessageContent):
"""Content for user memory input.
These are user messages containing user-memory-input tags.
Parsed by parse_user_memory() in parser.py, formatted by
format_user_memory_content() in html/user_formatters.py.
"""
# Memory-input framing — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
memory_text: str
@property
def message_type(self) -> str:
return "user"
@dataclass
class UserSlashCommandMessage(MessageContent):
"""Content for slash command expanded prompts (isMeta=True).
These are LLM-generated instruction text from slash commands.
The text is markdown formatted and rendered as such.
Formatted by format_user_slash_command_content() in html/user_formatters.py.
"""
# Slash-command expansion framing — visible only at HOOK.
depth_visibility: ClassVar[RenderingDepth] = RenderingDepth.HOOK
text: str
@property
def message_type(self) -> str:
return "user"
@dataclass
class IdeOpenedFile:
"""IDE notification for an opened file."""
content: str # Raw content from the tag
@dataclass
class IdeSelection:
"""IDE notification for a code selection."""
content: str # Raw selection content
@dataclass
class IdeDiagnostic:
"""IDE diagnostic notification.
Contains either parsed JSON diagnostics or raw content if parsing failed.
"""
diagnostics: Optional[list[dict[str, Any]]] = None # Parsed diagnostic objects
raw_content: Optional[str] = None # Fallback if JSON parsing failed
@dataclass
class IdeNotificationContent:
"""Content for IDE notification tags (embedded within user messages).
This is NOT a MessageContent subclass - it's used as an item within
UserTextMessage.items alongside TextContent and ImageContent.
Represents IDE notification tags like:
- <ide_opened_file>: File open notifications
- <ide_selection>: Code selection notifications
- <post-tool-use-hook><ide_diagnostics>: Diagnostic JSON arrays
Format-neutral: stores structured data, not HTML.
"""
opened_files: list[IdeOpenedFile]
selections: list[IdeSelection]
diagnostics: list[IdeDiagnostic]
remaining_text: str # Text after notifications extracted
@dataclass
class SystemReminderContent:
"""Content for ``<system-reminder>`` blocks embedded within user messages.
This is NOT a MessageContent subclass — like IdeNotificationContent it's an
item within UserTextMessage.items, alongside TextContent and ImageContent.
A user message may carry a system reminder (e.g. the ``/cd`` working-directory
notice) AND real content after it (e.g. a CLAUDE.md), so the reminder is
peeled out as an annotation while the remaining text renders as user content.
``reminders`` holds each reminder block's inner text (a message may carry
more than one). Format-neutral: stores text, not HTML.
"""
reminders: list[str]
@dataclass
class UserTextMessage(MessageContent):
"""Content for user text with interleaved images, IDE notifications, and
system reminders.
The `items` field preserves the original order of content:
- TextContent: Text portions of the message
- ImageContent: Inline images
- IdeNotificationContent: IDE notification tags (extracted from text)
- SystemReminderContent: <system-reminder> blocks (extracted from text)
Empty items list indicates no content.
"""
# Interleaved content items preserving original order
items: list[ # pyright: ignore[reportUnknownVariableType]
TextContent | ImageContent | IdeNotificationContent | SystemReminderContent
] = field(default_factory=list)
@property
def message_type(self) -> str:
return "user"
@dataclass
class UserSteeringMessage(UserTextMessage):
"""Content for user steering prompts (queue-operation "remove").
These are user messages that steer the conversation by removing
items from the queue. Inherits from UserTextMessage.
"""
pass
# A ``key: value`` line of a key/value teammate body (see
# ``TeammateMessageBlock.body_params``): identifier-like key, whitespace
# after the colon (so ``https://…`` is not a key), non-empty value.
# A data line's key looks like a field name (lowercase, as in the payloads
# peers send); a capitalised ``Label:`` opens a prose paragraph.
_KEY_VALUE_LINE_RE = re.compile(r"^\s*([a-z_][a-z0-9_.-]*)\s*:\s+(\S.*?)\s*$")
@dataclass
class TeammateMessageBlock:
"""A single <teammate-message> block extracted from a User entry
or from a peer agent queued_command attachment (#309).
`is_system=True` corresponds to blocks with teammate_id="system"
(e.g. teammate_terminated notifications).
`sender_task_id` is recorded for a future subagent transcript linker
(resolves to <session>/subagents/agent-<id>.jsonl when present; absent
on roughly a quarter of peer messages; unused by renderers today).
This is a plain data container — the renderer-facing MessageContent
wrapper is TeammateMessage (which holds one or more of these blocks).
"""
teammate_id: str
body: str
color: Optional[str] = None
summary: Optional[str] = None
is_system: bool = False
sender_task_id: Optional[str] = None
def body_params(self) -> Optional[dict[str, Any]]:
"""The body as key/value data, or None when it is prose.
A body is data when it is a non-empty JSON object (the
``idle_notification`` payloads) nested at most
``json_depth.MAX_DATA_DEPTH`` levels, or when every non-blank line is
``key: value`` with a lowercase field-name key (two lines at
least, no repeated key). Anything else, including prose whose
paragraphs open with ``Label: …``, stays Markdown.
"""
text = self.body.strip()
if text.startswith("{") and text.endswith("}"):
try:
parsed: Any = json.loads(text)
except (ValueError, RecursionError):
# RecursionError: nesting too deep for the decoder. The
# body then renders as prose rather than failing the page.
return None
if not isinstance(parsed, dict) or not parsed:
return None
if exceeds_depth(parsed):
return None
obj = cast("dict[Any, Any]", parsed)
return {str(k): v for k, v in obj.items()}
lines = [line for line in text.splitlines() if line.strip()]
if len(lines) < 2:
return None
params: dict[str, Any] = {}
for line in lines: