-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
687 lines (614 loc) · 17.9 KB
/
parser.go
File metadata and controls
687 lines (614 loc) · 17.9 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
// SPDX-Licence-Identifier: EUPL-1.2
package session
import (
"io" // Note: intrinsic — Reader, ReadCloser, and EOF contracts for transcript streams and hostFS handles; no core equivalent
"io/fs" // Note: intrinsic — fs.FileInfo metadata returned from hostFS.Stat; no core equivalent
"iter" // Note: intrinsic — public lazy sequence API for sessions and events; no core equivalent
"slices" // Note: intrinsic — iterator collection, sorted keys, and session ordering; no core equivalent
"time" // Note: intrinsic — RFC3339 transcript timestamps and session age calculations; no core equivalent
core "dappco.re/go/core"
coreerr "dappco.re/go/core/log"
)
// maxScannerBuffer is the maximum line length the scanner will accept.
// Set to 8 MiB to handle very large tool outputs without truncation.
const maxScannerBuffer = 8 * 1024 * 1024
// maxPendingToolCalls bounds unmatched tool_use entries retained while parsing.
const maxPendingToolCalls = 4096
// Event represents a single action in a session timeline.
//
// Example:
// evt := session.Event{Type: "tool_use", Tool: "Bash"}
type Event struct {
Timestamp time.Time
Type string // "tool_use", "user", "assistant", "error"
Tool string // "Bash", "Read", "Edit", "Write", "Grep", "Glob", etc.
ToolID string
Input string // Command, file path, or message text
Output string // Result text
Duration time.Duration
Success bool
ErrorMsg string
}
// Session holds parsed session metadata and events.
//
// Example:
// sess := &session.Session{ID: "abc123", Events: []session.Event{}}
type Session struct {
ID string
Path string
StartTime time.Time
EndTime time.Time
Events []Event
}
// EventsSeq returns an iterator over the session's events.
//
// Example:
//
// for evt := range sess.EventsSeq() {
// _ = evt
// }
func (s *Session) EventsSeq() iter.Seq[Event] {
return slices.Values(s.Events)
}
// rawEntry is the top-level structure of a Claude Code JSONL line.
type rawEntry struct {
Type string `json:"type"`
Timestamp string `json:"timestamp"`
SessionID string `json:"sessionId"`
Message rawJSON `json:"message"`
UserType string `json:"userType"`
}
type rawMessage struct {
Role string `json:"role"`
Content []rawJSON `json:"content"`
}
type contentBlock struct {
Type string `json:"type"`
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
Text string `json:"text,omitempty"`
Input rawJSON `json:"input,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
Content any `json:"content,omitempty"`
IsError *bool `json:"is_error,omitempty"`
}
type bashInput struct {
Command string `json:"command"`
Description string `json:"description"`
Timeout int `json:"timeout"`
}
type readInput struct {
FilePath string `json:"file_path"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
type editInput struct {
FilePath string `json:"file_path"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
}
type writeInput struct {
FilePath string `json:"file_path"`
Content string `json:"content"`
}
type grepInput struct {
Pattern string `json:"pattern"`
Path string `json:"path"`
}
type globInput struct {
Pattern string `json:"pattern"`
Path string `json:"path"`
}
type taskInput struct {
Prompt string `json:"prompt"`
Description string `json:"description"`
SubagentType string `json:"subagent_type"`
}
// ParseStats reports diagnostic information from a parse run.
//
// Example:
// stats := &session.ParseStats{TotalLines: 42}
type ParseStats struct {
TotalLines int
SkippedLines int
OrphanedToolCalls int
Warnings []string
}
// ListSessions returns all sessions found in the Claude projects directory.
//
// Example:
// sessions, err := session.ListSessions("/tmp/projects")
func ListSessions(projectsDir string) ([]Session, error) {
return slices.Collect(ListSessionsSeq(projectsDir)), nil
}
// ListSessionsSeq returns an iterator over all sessions found in the Claude projects directory.
//
// Example:
//
// for sess := range session.ListSessionsSeq("/tmp/projects") {
// _ = sess
// }
func ListSessionsSeq(projectsDir string) iter.Seq[Session] {
return func(yield func(Session) bool) {
const op = "ListSessionsSeq"
matches := core.PathGlob(transcriptPath(projectsDir, "*.jsonl"))
var sessions []Session
for _, filePath := range matches {
base := core.PathBase(filePath)
id := core.TrimSuffix(base, ".jsonl")
f, err := openTranscriptNoFollow(filePath)
if err != nil {
coreerr.Warn("skip unreadable transcript", "op", op, "path", filePath, "err", err)
continue
}
s := Session{
ID: id,
Path: filePath,
}
// Quick scan for first and last timestamps
var firstTS, lastTS string
scanErr := scanTranscriptLines(f, maxScannerBuffer, func(line []byte) bool {
var entry rawEntry
if !core.JSONUnmarshal(line, &entry).OK {
return true
}
if entry.Timestamp == "" {
return true
}
if firstTS == "" {
firstTS = entry.Timestamp
}
lastTS = entry.Timestamp
return true
})
closeErr := f.Close()
if scanErr != nil {
coreerr.Warn("skip unreadable transcript", "op", op, "path", filePath, "err", scanErr)
continue
}
if closeErr != nil {
coreerr.Warn("skip unreadable transcript", "op", op, "path", filePath, "err", closeErr)
continue
}
if firstTS != "" {
if t, err := time.Parse(time.RFC3339Nano, firstTS); err == nil {
s.StartTime = t
}
}
if lastTS != "" {
if t, err := time.Parse(time.RFC3339Nano, lastTS); err == nil {
s.EndTime = t
}
}
if s.StartTime.IsZero() {
infoResult := hostFS.Stat(filePath)
if infoResult.OK {
if info, ok := infoResult.Value.(fs.FileInfo); ok {
s.StartTime = info.ModTime()
}
}
}
sessions = append(sessions, s)
}
slices.SortFunc(sessions, func(i, j Session) int {
return j.StartTime.Compare(i.StartTime)
})
for _, s := range sessions {
if !yield(s) {
return
}
}
}
}
// PruneSessions deletes session files in the projects directory that were last
// modified more than maxAge ago. Returns the number of files deleted.
//
// Example:
// deleted, err := session.PruneSessions("/tmp/projects", 24*time.Hour)
func PruneSessions(projectsDir string, maxAge time.Duration) (int, error) {
matches := core.PathGlob(transcriptPath(projectsDir, "*.jsonl"))
var deleted int
now := time.Now()
for _, filePath := range matches {
infoResult := hostFS.Stat(filePath)
if !infoResult.OK {
continue
}
info, ok := infoResult.Value.(fs.FileInfo)
if !ok {
continue
}
if now.Sub(info.ModTime()) > maxAge {
if deleteResult := hostFS.Delete(filePath); deleteResult.OK {
deleted++
}
}
}
return deleted, nil
}
// IsExpired returns true if the session's end time is older than the given maxAge
// relative to now.
//
// Example:
// expired := sess.IsExpired(24 * time.Hour)
func (s *Session) IsExpired(maxAge time.Duration) bool {
if s.EndTime.IsZero() {
return false
}
return time.Since(s.EndTime) > maxAge
}
// FetchSession retrieves a session by ID from the projects directory.
// It ensures the ID does not contain path traversal characters.
//
// Example:
// sess, stats, err := session.FetchSession("/tmp/projects", "abc123")
func FetchSession(projectsDir, id string) (*Session, *ParseStats, error) {
if core.Contains(id, "..") || containsAny(id, `/\`) {
return nil, nil, coreerr.E("FetchSession", "invalid session id", nil)
}
filePath := transcriptPath(projectsDir, id+".jsonl")
f, err := openTranscriptNoFollow(filePath)
if err != nil {
if isTranscriptMissing(err) {
return nil, nil, coreerr.E("FetchSession", "open transcript", err)
}
return nil, nil, coreerr.E("FetchSession", "invalid session path", err)
}
defer func() {
_ = f.Close()
}()
return parseTranscriptFile(filePath, f)
}
// ParseTranscript reads a JSONL session file and returns structured events.
// Malformed or truncated lines are skipped; diagnostics are reported in ParseStats.
//
// Example:
// sess, stats, err := session.ParseTranscript("/tmp/projects/abc123.jsonl")
func ParseTranscript(filePath string) (*Session, *ParseStats, error) {
openResult := hostFS.Open(filePath)
if !openResult.OK {
return nil, nil, coreerr.E("ParseTranscript", "open transcript", resultError(openResult))
}
f, ok := openResult.Value.(io.ReadCloser)
if !ok {
return nil, nil, coreerr.E("ParseTranscript", "unexpected file handle type", nil)
}
defer func() {
_ = f.Close()
}()
return parseTranscriptFile(filePath, f)
}
// parseTranscriptFile parses an already-open transcript reader and assigns path metadata.
func parseTranscriptFile(filePath string, r io.Reader) (*Session, *ParseStats, error) {
base := core.PathBase(filePath)
id := core.TrimSuffix(base, ".jsonl")
sess, stats, err := parseFromReader(r, id)
if sess != nil {
sess.Path = filePath
}
if err != nil {
return sess, stats, coreerr.E("ParseTranscript", "parse transcript", err)
}
return sess, stats, nil
}
// ParseTranscriptReader parses a JSONL session from an io.Reader, enabling
// streaming parse without needing a file on disc. The id parameter sets
// the session ID (since there is no file name to derive it from).
//
// Example:
// sess, stats, err := session.ParseTranscriptReader(reader, "abc123")
func ParseTranscriptReader(r io.Reader, id string) (*Session, *ParseStats, error) {
sess, stats, err := parseFromReader(r, id)
if err != nil {
return sess, stats, coreerr.E("ParseTranscriptReader", "parse transcript", err)
}
return sess, stats, nil
}
// parseFromReader is the shared implementation for both file-based and
// reader-based parsing. It scans line-by-line with an 8 MiB buffer,
// gracefully skipping malformed lines.
func parseFromReader(r io.Reader, id string) (*Session, *ParseStats, error) {
sess := &Session{
ID: id,
}
stats := &ParseStats{}
// Collect tool_use entries keyed by ID.
type toolUse struct {
timestamp time.Time
tool string
input string
}
pendingTools := make(map[string]toolUse)
var lineNum int
var lastRaw string
var lastLineFailed bool
scanErr := scanTranscriptLines(r, maxScannerBuffer, func(line []byte) bool {
lineNum++
stats.TotalLines++
raw := string(line)
if core.Trim(raw) == "" {
return true
}
lastRaw = raw
lastLineFailed = false
var entry rawEntry
if !core.JSONUnmarshalString(raw, &entry).OK {
stats.SkippedLines++
preview := raw
if len(preview) > 100 {
preview = preview[:100]
}
stats.Warnings = append(stats.Warnings,
core.Sprintf("line %d: skipped (bad JSON): %s", lineNum, preview))
lastLineFailed = true
return true
}
ts, err := time.Parse(time.RFC3339Nano, entry.Timestamp)
if err != nil {
stats.Warnings = append(stats.Warnings, core.Sprintf("line %d: bad timestamp %q: %v", lineNum, entry.Timestamp, err))
return true
}
if sess.StartTime.IsZero() && !ts.IsZero() {
sess.StartTime = ts
}
if !ts.IsZero() {
sess.EndTime = ts
}
switch entry.Type {
case "assistant":
var msg rawMessage
if !core.JSONUnmarshal(entry.Message, &msg).OK {
stats.Warnings = append(stats.Warnings, core.Sprintf("line %d: failed to unmarshal assistant message", lineNum))
return true
}
for i, raw := range msg.Content {
var block contentBlock
if !core.JSONUnmarshal(raw, &block).OK {
stats.Warnings = append(stats.Warnings, core.Sprintf("line %d block %d: failed to unmarshal content", lineNum, i))
continue
}
switch block.Type {
case "text":
if text := core.Trim(block.Text); text != "" {
sess.Events = append(sess.Events, Event{
Timestamp: ts,
Type: "assistant",
Input: truncate(text, 500),
})
}
case "tool_use":
if block.ID == "" {
continue
}
if _, exists := pendingTools[block.ID]; !exists && len(pendingTools) >= maxPendingToolCalls {
stats.Warnings = append(stats.Warnings,
core.Sprintf("line %d: skipped tool_use %q (pending tool limit reached)", lineNum, block.ID))
continue
}
inputStr := extractToolInput(block.Name, block.Input)
pendingTools[block.ID] = toolUse{
timestamp: ts,
tool: block.Name,
input: truncate(inputStr, 500),
}
}
}
case "user":
var msg rawMessage
if !core.JSONUnmarshal(entry.Message, &msg).OK {
stats.Warnings = append(stats.Warnings, core.Sprintf("line %d: failed to unmarshal user message", lineNum))
return true
}
for i, raw := range msg.Content {
var block contentBlock
if !core.JSONUnmarshal(raw, &block).OK {
stats.Warnings = append(stats.Warnings, core.Sprintf("line %d block %d: failed to unmarshal content", lineNum, i))
continue
}
switch block.Type {
case "tool_result":
if tu, ok := pendingTools[block.ToolUseID]; ok {
output := extractResultContent(block.Content)
isError := block.IsError != nil && *block.IsError
evt := Event{
Timestamp: tu.timestamp,
Type: "tool_use",
Tool: tu.tool,
ToolID: block.ToolUseID,
Input: tu.input,
Output: truncate(output, 2000),
Duration: ts.Sub(tu.timestamp),
Success: !isError,
}
if isError {
evt.ErrorMsg = truncate(output, 500)
}
sess.Events = append(sess.Events, evt)
delete(pendingTools, block.ToolUseID)
}
case "text":
if text := core.Trim(block.Text); text != "" {
sess.Events = append(sess.Events, Event{
Timestamp: ts,
Type: "user",
Input: truncate(text, 500),
})
}
}
}
}
return true
})
// Detect truncated final line.
if lastLineFailed && lastRaw != "" {
stats.Warnings = append(stats.Warnings, "truncated final line")
}
if scanErr != nil {
return nil, stats, scanErr
}
// Track orphaned tool calls (tool_use with no matching result).
stats.OrphanedToolCalls = len(pendingTools)
if stats.OrphanedToolCalls > 0 {
for id := range pendingTools {
stats.Warnings = append(stats.Warnings,
core.Sprintf("orphaned tool call: %s", id))
}
}
return sess, stats, nil
}
// extractToolInput converts raw Claude tool input into a concise display string.
func extractToolInput(toolName string, raw rawJSON) string {
if raw == nil {
return ""
}
switch toolName {
case "Bash":
var inp bashInput
if core.JSONUnmarshal(raw, &inp).OK {
desc := inp.Description
if desc != "" {
desc = " # " + desc
}
return inp.Command + desc
}
case "Read":
var inp readInput
if core.JSONUnmarshal(raw, &inp).OK {
return inp.FilePath
}
case "Edit":
var inp editInput
if core.JSONUnmarshal(raw, &inp).OK {
return core.Sprintf("%s (edit)", inp.FilePath)
}
case "Write":
var inp writeInput
if core.JSONUnmarshal(raw, &inp).OK {
return core.Sprintf("%s (%d bytes)", inp.FilePath, len(inp.Content))
}
case "Grep":
var inp grepInput
if core.JSONUnmarshal(raw, &inp).OK {
path := inp.Path
if path == "" {
path = "."
}
return core.Sprintf("/%s/ in %s", inp.Pattern, path)
}
case "Glob":
var inp globInput
if core.JSONUnmarshal(raw, &inp).OK {
return inp.Pattern
}
case "Task":
var inp taskInput
if core.JSONUnmarshal(raw, &inp).OK {
desc := inp.Description
if desc == "" {
desc = truncate(inp.Prompt, 80)
}
return core.Sprintf("[%s] %s", inp.SubagentType, desc)
}
}
// Fallback: show raw JSON keys
var m map[string]any
if core.JSONUnmarshal(raw, &m).OK {
parts := make([]string, 0, len(m))
for key := range m {
parts = append(parts, key)
}
slices.Sort(parts)
return core.Join(", ", parts...)
}
return ""
}
// extractResultContent converts Claude tool_result content into plain text.
func extractResultContent(content any) string {
switch v := content.(type) {
case string:
return v
case []any:
var parts []string
for _, item := range v {
if m, ok := item.(map[string]any); ok {
if text, ok := m["text"].(string); ok {
parts = append(parts, text)
}
}
}
return core.Join("\n", parts...)
case map[string]any:
if text, ok := v["text"].(string); ok {
return text
}
}
return core.Sprint(content)
}
// truncate returns s capped to max bytes with an ellipsis marker.
func truncate(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max] + "..."
}
// scanTranscriptLines streams newline-delimited records with a per-line size limit.
func scanTranscriptLines(r io.Reader, maxLineSize int, handle func([]byte) bool) error {
const op = "scanTranscriptLines"
if maxLineSize <= 0 {
maxLineSize = maxScannerBuffer
}
readBuffer := make([]byte, 64*1024)
line := make([]byte, 0, 64*1024)
for {
n, readErr := r.Read(readBuffer)
if n > 0 {
chunk := readBuffer[:n]
start := 0
for i, b := range chunk {
if b != '\n' {
continue
}
if len(line)+i-start > maxLineSize {
return coreerr.E(op, core.Sprintf("line exceeds %d bytes", maxLineSize), nil)
}
line = append(line, chunk[start:i]...)
if !handle(trimLineBreak(line)) {
return nil
}
line = line[:0]
start = i + 1
}
if start < len(chunk) {
if len(line)+len(chunk)-start > maxLineSize {
return coreerr.E(op, core.Sprintf("line exceeds %d bytes", maxLineSize), nil)
}
line = append(line, chunk[start:]...)
}
}
if readErr == io.EOF {
if len(line) > 0 {
if !handle(trimLineBreak(line)) {
return nil
}
}
return nil
}
if readErr != nil {
return coreerr.E(op, "read error", readErr)
}
}
}
// trimLineBreak removes a trailing carriage return from a scanned line.
func trimLineBreak(line []byte) []byte {
if len(line) > 0 && line[len(line)-1] == '\r' {
return line[:len(line)-1]
}
return line
}
// transcriptPath joins a projects directory and transcript file name.
func transcriptPath(projectsDir, name string) string {
if projectsDir == "" {
return core.CleanPath(name, "/")
}
return core.CleanPath(core.JoinPath(projectsDir, name), "/")
}