-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathhermes.go
More file actions
1213 lines (1114 loc) · 33.2 KB
/
Copy pathhermes.go
File metadata and controls
1213 lines (1114 loc) · 33.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
// ABOUTME: Parses Hermes Agent JSONL session files into structured session data.
// ABOUTME: Handles Hermes's OpenAI-style message format with session_meta header,
// ABOUTME: user/assistant/tool roles, and function-call tool invocations.
package parser
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"math"
"os"
"path/filepath"
"sort"
"strings"
"time"
_ "github.com/mattn/go-sqlite3"
"github.com/tidwall/gjson"
)
type hermesStateSession struct {
id string
source string
model string
parentSessionID string
startedAt time.Time
endedAt time.Time
messageCount int
inputTokens int
outputTokens int
cacheReadTokens int
cacheWriteTokens int
reasoningTokens int
estimatedCost sql.NullFloat64
actualCost sql.NullFloat64
costStatus string
costSource string
title string
apiCallCount int
}
type hermesStateMessage struct {
role string
content string
toolCallID string
toolCalls string
timestamp time.Time
finishReason string
reasoning string
reasoningContent string
reasoningDetails string
codexReasoningItems string
codexMessageItems string
}
// parseArchive parses a Hermes root directory. If a state.db is present, it
// uses that database for session metadata and usage while selecting the richest
// available message stream. Without state.db it falls back to the
// transcript-file parser. It owns the archive on-disk shape (state.db plus the
// sessions transcript directory) for the Hermes provider; the package-level
// entrypoint was folded onto the provider.
func (p *hermesProvider) parseArchive(root, project, machine string) ([]ParseResult, error) {
stateDB, sessionsDir, ok := hermesStatePaths(root)
if !ok {
return p.parseTranscriptArchive(root, project, machine)
}
results, err := p.parseStateDB(
stateDB, sessionsDir, project, machine,
)
if err == nil {
return results, nil
}
log.Printf(
"hermes: state db parse failed for %s: %v; falling back to transcripts",
stateDB, err,
)
return p.parseTranscriptArchive(
sessionsDir, project, machine,
)
}
func (p *hermesProvider) parseTranscriptArchive(
root, project, machine string,
) ([]ParseResult, error) {
var results []ParseResult
for _, file := range discoverHermesTranscriptFiles(root) {
fileProject := file.Project
if project != "" {
fileProject = project
}
sess, msgs, err := p.parseSession(
file.Path, fileProject, machine,
)
if err != nil {
return nil, err
}
if sess != nil {
results = append(results, ParseResult{
Session: *sess, Messages: msgs,
})
}
}
return results, nil
}
// parseSession parses a Hermes Agent session file. It owns the on-disk shape
// (flat JSONL transcripts plus session_*.json snapshots) for the Hermes
// provider; the package-level entrypoint was folded onto the provider.
//
// Hermes stores sessions as flat JSONL files in ~/.hermes/sessions/
// with filenames like 20260403_153620_5a3e2ff1.jsonl.
//
// Line format:
// - First line: {"role":"session_meta", "tools":[...], "model":"...", "platform":"...", "timestamp":"..."}
// - User messages: {"role":"user", "content":"...", "timestamp":"..."}
// - Assistant messages: {"role":"assistant", "content":"...", "reasoning":"...",
// "finish_reason":"tool_calls|stop", "tool_calls":[...], "timestamp":"..."}
// - Tool results: {"role":"tool", "content":"...", "tool_call_id":"...", "timestamp":"..."}
func (p *hermesProvider) parseSession(path, project, machine string) (*ParsedSession, []ParsedMessage, error) {
if strings.HasSuffix(path, ".json") {
return parseHermesJSONSession(path, project, machine)
}
return parseHermesJSONLSession(path, project, machine)
}
// parseHermesJSONLSession parses a Hermes Agent JSONL session file.
func parseHermesJSONLSession(path, project, machine string) (*ParsedSession, []ParsedMessage, error) {
info, err := os.Stat(path)
if err != nil {
return nil, nil, fmt.Errorf("stat %s: %w", path, err)
}
f, err := os.Open(path)
if err != nil {
return nil, nil, fmt.Errorf("open %s: %w", path, err)
}
defer f.Close()
lr := newLineReader(f, maxLineSize)
var (
messages []ParsedMessage
startedAt time.Time
endedAt time.Time
ordinal int
realUserCount int
firstMsg string
sessionPlatform string
)
// Extract session ID from filename: 20260403_153620_5a3e2ff1.jsonl -> 20260403_153620_5a3e2ff1
sessionID := HermesSessionID(filepath.Base(path))
for {
line, ok := lr.next()
if !ok {
break
}
if !gjson.Valid(line) {
continue
}
role := gjson.Get(line, "role").Str
ts := parseHermesTimestamp(gjson.Get(line, "timestamp").Str)
if !ts.IsZero() {
if startedAt.IsZero() || ts.Before(startedAt) {
startedAt = ts
}
if ts.After(endedAt) {
endedAt = ts
}
}
switch role {
case "session_meta":
// Extract model and platform from session header.
sessionPlatform = gjson.Get(line, "platform").Str
continue
case "user":
content := gjson.Get(line, "content").Str
content = strings.TrimSpace(content)
if content == "" {
continue
}
// Strip skill injection prefixes for cleaner display.
displayContent := stripHermesSkillPrefix(content)
isCompact := isHermesCompactBoundary(displayContent)
if firstMsg == "" && displayContent != "" && !isCompact {
firstMsg = truncate(
strings.ReplaceAll(displayContent, "\n", " "),
300,
)
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Content: displayContent,
Timestamp: ts,
ContentLength: len(content),
IsSystem: isCompact,
SourceType: sourceTypeIf(isCompact, "system"),
SourceSubtype: sourceTypeIf(isCompact, "compact_boundary"),
IsCompactBoundary: isCompact,
})
ordinal++
if !isCompact {
realUserCount++
}
case "assistant":
content := gjson.Get(line, "content").Str
content = strings.TrimSpace(content)
reasoning := gjson.Get(line, "reasoning").Str
hasThinking := reasoning != ""
// Extract tool calls from the assistant message.
var toolCalls []ParsedToolCall
tcArray := gjson.Get(line, "tool_calls")
if tcArray.IsArray() {
tcArray.ForEach(func(_, tc gjson.Result) bool {
name := tc.Get("function.name").Str
if name != "" {
toolCalls = append(toolCalls, ParsedToolCall{
ToolUseID: tc.Get("id").Str,
ToolName: name,
Category: NormalizeToolCategory(name),
InputJSON: tc.Get("function.arguments").Str,
})
}
return true
})
}
hasToolUse := len(toolCalls) > 0
// Build display content: include reasoning if present.
displayContent := content
if hasThinking && content == "" {
// Assistant message with only reasoning and tool calls.
displayContent = ""
}
if hasThinking {
displayContent = "[Thinking]\n" + reasoning + "\n[/Thinking]\n" + displayContent
}
if displayContent == "" && len(toolCalls) == 0 {
continue
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleAssistant,
Content: displayContent,
Timestamp: ts,
HasThinking: hasThinking,
HasToolUse: hasToolUse,
ContentLength: len(content) + len(reasoning),
ToolCalls: toolCalls,
})
ordinal++
case "tool":
// Tool results in Hermes are separate messages with
// tool_call_id linking back to the assistant's tool call.
toolCallID := gjson.Get(line, "tool_call_id").Str
if toolCallID == "" {
continue
}
content := gjson.Get(line, "content").Str
contentLen := len(content)
// Preserve tool output as JSON-quoted string so
// pairToolResults / DecodeContent can surface it in the UI.
quoted, _ := json.Marshal(content)
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Content: "",
Timestamp: ts,
ContentLength: contentLen,
ToolResults: []ParsedToolResult{{
ToolUseID: toolCallID,
ContentRaw: string(quoted),
ContentLength: contentLen,
}},
})
ordinal++
}
}
if err := lr.Err(); err != nil {
return nil, nil, fmt.Errorf("reading %s: %w", path, err)
}
if len(messages) == 0 {
return nil, nil, nil
}
fullID := "hermes:" + sessionID
// Derive project from the session platform or default.
if project == "" {
if sessionPlatform != "" {
project = "hermes-" + sessionPlatform
} else {
project = "hermes"
}
}
sess := &ParsedSession{
ID: fullID,
Project: project,
Machine: machine,
Agent: AgentHermes,
FirstMessage: firstMsg,
StartedAt: startedAt,
EndedAt: endedAt,
MessageCount: len(messages),
UserMessageCount: realUserCount,
File: FileInfo{
Path: path,
Size: info.Size(),
Mtime: info.ModTime().UnixNano(),
},
}
return sess, messages, nil
}
// parseHermesJSONSession parses a Hermes CLI-format JSON session file.
func parseHermesJSONSession(path, project, machine string) (*ParsedSession, []ParsedMessage, error) {
info, err := os.Stat(path)
if err != nil {
return nil, nil, fmt.Errorf("stat %s: %w", path, err)
}
data, err := os.ReadFile(path)
if err != nil {
return nil, nil, fmt.Errorf("read %s: %w", path, err)
}
root := gjson.ParseBytes(data)
if !root.IsObject() {
return nil, nil, fmt.Errorf("invalid JSON in %s", path)
}
sessionID := HermesSessionID(filepath.Base(path))
sessionPlatform := root.Get("platform").Str
startedAt := parseHermesTimestamp(root.Get("session_start").Str)
endedAt := parseHermesTimestamp(root.Get("last_updated").Str)
var (
messages []ParsedMessage
ordinal int
realUserCount int
firstMsg string
)
root.Get("messages").ForEach(func(_, msg gjson.Result) bool {
role := msg.Get("role").Str
// Extract per-message timestamp when available.
msgTS := parseHermesTimestamp(msg.Get("timestamp").Str)
// Reconcile per-message timestamps with session bounds so
// StartedAt/EndedAt stay correct even if envelope fields
// are missing or stale.
if !msgTS.IsZero() {
if startedAt.IsZero() || msgTS.Before(startedAt) {
startedAt = msgTS
}
if msgTS.After(endedAt) {
endedAt = msgTS
}
}
switch role {
case "user":
content := strings.TrimSpace(msg.Get("content").Str)
if content == "" {
return true
}
displayContent := stripHermesSkillPrefix(content)
isCompact := isHermesCompactBoundary(displayContent)
if firstMsg == "" && displayContent != "" && !isCompact {
firstMsg = truncate(
strings.ReplaceAll(displayContent, "\n", " "),
300,
)
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Content: displayContent,
Timestamp: msgTS,
ContentLength: len(content),
IsSystem: isCompact,
SourceType: sourceTypeIf(isCompact, "system"),
SourceSubtype: sourceTypeIf(isCompact, "compact_boundary"),
IsCompactBoundary: isCompact,
})
ordinal++
if !isCompact {
realUserCount++
}
case "assistant":
content := strings.TrimSpace(msg.Get("content").Str)
reasoning := msg.Get("reasoning").Str
if reasoning == "" {
reasoning = msg.Get("reasoning_details").Str
}
hasThinking := reasoning != ""
var toolCalls []ParsedToolCall
tcArray := msg.Get("tool_calls")
if tcArray.IsArray() {
tcArray.ForEach(func(_, tc gjson.Result) bool {
name := tc.Get("function.name").Str
if name != "" {
toolCalls = append(toolCalls, ParsedToolCall{
ToolUseID: tc.Get("id").Str,
ToolName: name,
Category: NormalizeToolCategory(name),
InputJSON: tc.Get("function.arguments").Str,
})
}
return true
})
}
hasToolUse := len(toolCalls) > 0
displayContent := content
if hasThinking && content == "" {
displayContent = ""
}
if hasThinking {
displayContent = "[Thinking]\n" + reasoning + "\n[/Thinking]\n" + displayContent
}
if displayContent == "" && len(toolCalls) == 0 {
return true
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleAssistant,
Content: displayContent,
Timestamp: msgTS,
HasThinking: hasThinking,
HasToolUse: hasToolUse,
ContentLength: len(content) + len(reasoning),
ToolCalls: toolCalls,
})
ordinal++
case "tool":
toolCallID := msg.Get("tool_call_id").Str
if toolCallID == "" {
return true
}
content := msg.Get("content").Str
contentLen := len(content)
// Preserve tool output as JSON-quoted string so
// pairToolResults / DecodeContent can surface it in the UI.
quoted, _ := json.Marshal(content)
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Content: "",
Timestamp: msgTS,
ContentLength: contentLen,
ToolResults: []ParsedToolResult{{
ToolUseID: toolCallID,
ContentRaw: string(quoted),
ContentLength: contentLen,
}},
})
ordinal++
}
return true
})
if len(messages) == 0 {
return nil, nil, nil
}
fullID := "hermes:" + sessionID
if project == "" {
if sessionPlatform != "" {
project = "hermes-" + sessionPlatform
} else {
project = "hermes"
}
}
sess := &ParsedSession{
ID: fullID,
Project: project,
Machine: machine,
Agent: AgentHermes,
FirstMessage: firstMsg,
StartedAt: startedAt,
EndedAt: endedAt,
MessageCount: len(messages),
UserMessageCount: realUserCount,
File: FileInfo{
Path: path,
Size: info.Size(),
Mtime: info.ModTime().UnixNano(),
},
}
return sess, messages, nil
}
func hermesStatePaths(root string) (stateDB, sessionsDir string, ok bool) {
if root == "" {
return "", "", false
}
info, err := os.Stat(root)
if err == nil && !info.IsDir() &&
filepath.Base(root) == "state.db" {
dir := filepath.Dir(root)
return root, filepath.Join(dir, "sessions"), true
}
if st := filepath.Join(root, "state.db"); IsRegularFile(st) {
return st, filepath.Join(root, "sessions"), true
}
if filepath.Base(root) == "sessions" {
parent := filepath.Dir(root)
st := filepath.Join(parent, "state.db")
if IsRegularFile(st) {
return st, root, true
}
}
return "", "", false
}
func (p *hermesProvider) parseStateDB(
stateDB, sessionsDir, project, machine string,
) ([]ParseResult, error) {
conn, err := sql.Open("sqlite3", "file:"+stateDB+"?mode=ro")
if err != nil {
return nil, fmt.Errorf("open hermes state db: %w", err)
}
defer conn.Close()
sessions, err := readHermesStateSessions(conn)
if err != nil {
return nil, err
}
messages, err := readHermesStateMessages(conn)
if err != nil {
return nil, err
}
var results []ParseResult
seen := make(map[string]struct{}, len(sessions))
for _, ss := range sessions {
res, ok := buildHermesStateResult(
ss, messages[ss.id], sessionsDir, stateDB, project, machine,
)
if ok {
results = append(results, res)
seen[ss.id] = struct{}{}
}
}
for _, file := range discoverHermesTranscriptFiles(sessionsDir) {
rawID := HermesSessionID(filepath.Base(file.Path))
if _, ok := seen[rawID]; ok {
continue
}
sess, msgs, err := p.parseSession(
file.Path, file.Project, machine,
)
if err != nil {
return nil, err
}
if sess != nil {
results = append(results, ParseResult{
Session: *sess, Messages: msgs,
})
}
}
sort.Slice(results, func(i, j int) bool {
return results[i].Session.ID < results[j].Session.ID
})
return results, nil
}
func readHermesStateSessions(
conn *sql.DB,
) ([]hermesStateSession, error) {
rows, err := conn.Query(`
SELECT id, source, COALESCE(model, ''),
COALESCE(parent_session_id, ''), started_at,
COALESCE(ended_at, 0), COALESCE(message_count, 0),
COALESCE(input_tokens, 0), COALESCE(output_tokens, 0),
COALESCE(cache_read_tokens, 0),
COALESCE(cache_write_tokens, 0),
COALESCE(reasoning_tokens, 0),
estimated_cost_usd, actual_cost_usd,
COALESCE(cost_status, ''), COALESCE(cost_source, ''),
COALESCE(title, ''), COALESCE(api_call_count, 0)
FROM sessions
ORDER BY started_at ASC, id ASC`)
if err != nil {
return nil, fmt.Errorf("query hermes sessions: %w", err)
}
defer rows.Close()
var out []hermesStateSession
for rows.Next() {
var ss hermesStateSession
var started, ended float64
if err := rows.Scan(
&ss.id, &ss.source, &ss.model,
&ss.parentSessionID, &started, &ended,
&ss.messageCount, &ss.inputTokens, &ss.outputTokens,
&ss.cacheReadTokens, &ss.cacheWriteTokens,
&ss.reasoningTokens, &ss.estimatedCost, &ss.actualCost,
&ss.costStatus, &ss.costSource, &ss.title,
&ss.apiCallCount,
); err != nil {
return nil, fmt.Errorf("scan hermes session: %w", err)
}
ss.startedAt = hermesUnixTime(started)
ss.endedAt = hermesUnixTime(ended)
out = append(out, ss)
}
return out, rows.Err()
}
func readHermesStateMessages(
conn *sql.DB,
) (map[string][]hermesStateMessage, error) {
rows, err := conn.Query(`
SELECT session_id, role, COALESCE(content, ''),
COALESCE(tool_call_id, ''), COALESCE(tool_calls, ''),
timestamp, COALESCE(finish_reason, ''),
COALESCE(reasoning, ''), COALESCE(reasoning_content, ''),
COALESCE(reasoning_details, ''),
COALESCE(codex_reasoning_items, ''),
COALESCE(codex_message_items, '')
FROM messages
ORDER BY session_id ASC, timestamp ASC, id ASC`)
if err != nil {
return nil, fmt.Errorf("query hermes messages: %w", err)
}
defer rows.Close()
out := make(map[string][]hermesStateMessage)
for rows.Next() {
var sid string
var hm hermesStateMessage
var ts float64
if err := rows.Scan(
&sid, &hm.role, &hm.content, &hm.toolCallID,
&hm.toolCalls, &ts, &hm.finishReason,
&hm.reasoning, &hm.reasoningContent,
&hm.reasoningDetails, &hm.codexReasoningItems,
&hm.codexMessageItems,
); err != nil {
return nil, fmt.Errorf("scan hermes message: %w", err)
}
hm.timestamp = hermesUnixTime(ts)
out[sid] = append(out[sid], hm)
}
return out, rows.Err()
}
func buildHermesStateResult(
ss hermesStateSession, stateMessages []hermesStateMessage,
sessionsDir, stateDB, project, machine string,
) (ParseResult, bool) {
jsonPath := filepath.Join(sessionsDir, "session_"+ss.id+".json")
jsonlPath := filepath.Join(sessionsDir, ss.id+".jsonl")
var sess *ParsedSession
var msgs []ParsedMessage
var err error
selectedPath := stateDB
if IsRegularFile(jsonPath) {
sess, msgs, err = parseHermesJSONSession(jsonPath, project, machine)
if err == nil && sess != nil &&
hermesMessageQuality(msgs) >= hermesStateQuality(stateMessages) {
selectedPath = jsonPath
} else {
sess, msgs = nil, nil
}
}
if sess == nil && IsRegularFile(jsonlPath) {
sess, msgs, err = parseHermesJSONLSession(jsonlPath, project, machine)
if err == nil && sess != nil &&
(hermesMessageQuality(msgs) >= hermesStateQuality(stateMessages) || len(stateMessages) == 0) {
selectedPath = jsonlPath
} else {
sess, msgs = nil, nil
}
}
usageEvents := hermesUsageEvents(ss, "hermes:"+ss.id)
if sess == nil {
msgs = convertHermesStateMessages(stateMessages)
if len(msgs) == 0 && len(usageEvents) == 0 {
return ParseResult{}, false
}
sess = &ParsedSession{
ID: "hermes:" + ss.id,
Agent: AgentHermes,
Machine: machine,
StartedAt: ss.startedAt,
EndedAt: ss.endedAt,
MessageCount: len(msgs),
UserMessageCount: countHermesUsers(msgs),
FirstMessage: firstHermesMessage(msgs),
}
}
applyHermesStateMetadata(sess, ss, selectedPath, project)
return ParseResult{
Session: *sess,
Messages: msgs,
UsageEvents: usageEvents,
}, true
}
func applyHermesStateMetadata(
sess *ParsedSession, ss hermesStateSession, selectedPath, project string,
) {
sess.ID = "hermes:" + ss.id
sess.Agent = AgentHermes
if project != "" {
sess.Project = project
} else if ss.source != "" {
sess.Project = "hermes-" + ss.source
} else if sess.Project == "" {
sess.Project = "hermes"
}
if !ss.startedAt.IsZero() {
sess.StartedAt = ss.startedAt
}
if !ss.endedAt.IsZero() {
sess.EndedAt = ss.endedAt
}
if ss.parentSessionID != "" {
sess.ParentSessionID = "hermes:" + ss.parentSessionID
sess.RelationshipType = RelContinuation
}
sess.SourceSessionID = ss.id
sess.SourceVersion = "hermes-state-db"
sess.SessionName = ss.title
// Populate the session-aggregate token columns from Hermes's own
// authoritative state.db accounting. These feed the session list,
// session detail, and stats portfolio, which read the aggregate
// fields directly and do not fall back to usage_events. The
// transcript paths yield 0 here (per-message token_count is 0 in
// state.db), so these values are strictly better; set them
// unconditionally when present. PeakContextTokens uses the
// cumulative input + cache_read approximation (matching forge's
// convention); a truer last-prompt peak lives only in sessions.json.
if ss.outputTokens > 0 {
sess.TotalOutputTokens = ss.outputTokens
sess.HasTotalOutputTokens = true
}
if ctx := ss.inputTokens + ss.cacheReadTokens; ctx > 0 {
sess.PeakContextTokens = ctx
sess.HasPeakContextTokens = true
}
sess.aggregateTokenPresenceKnown =
sess.HasTotalOutputTokens || sess.HasPeakContextTokens
if selectedPath != "" {
if info, err := os.Stat(selectedPath); err == nil {
sess.File = FileInfo{
Path: selectedPath,
Size: info.Size(),
Mtime: info.ModTime().UnixNano(),
}
}
}
}
// hermesHasCostSource reports whether a Hermes cost_source represents a
// real cost determination. "none" (and empty) mean Hermes had no basis
// for the figure, so a $0 it pairs with cost_status "included" is a
// default placeholder rather than a confident free-usage signal.
func hermesHasCostSource(costSource string) bool {
return costSource != "" && costSource != "none"
}
func hermesUsageEvents(
ss hermesStateSession, sessionID string,
) []ParsedUsageEvent {
if ss.model == "" {
return nil
}
if ss.inputTokens == 0 && ss.outputTokens == 0 &&
ss.cacheReadTokens == 0 && ss.cacheWriteTokens == 0 &&
ss.reasoningTokens == 0 && !ss.estimatedCost.Valid &&
!ss.actualCost.Valid {
return nil
}
// Only emit a cost_usd when Hermes actually knows it. Otherwise
// leave it nil so agentsview prices the row from its own model
// catalog. A "included" cost_status is a genuine known $0 only when
// a real cost_source backs it; Hermes also emits "included" with
// cost_source "none" (or empty) as a default for models it does not
// price (e.g. gpt-5.5), which is NOT a confident $0 and must fall
// through to catalog pricing. Likewise "unknown"/empty with a 0
// estimate is not a real figure and must not masquerade as $0.
var cost *float64
switch {
case ss.actualCost.Valid:
v := ss.actualCost.Float64
cost = &v
case ss.costStatus == "included" && hermesHasCostSource(ss.costSource):
zero := 0.0
cost = &zero
case ss.estimatedCost.Valid && ss.estimatedCost.Float64 > 0:
v := ss.estimatedCost.Float64
cost = &v
}
return []ParsedUsageEvent{{
SessionID: sessionID,
Source: "session",
Model: ss.model,
InputTokens: max(ss.inputTokens, 0),
OutputTokens: max(ss.outputTokens, 0),
CacheCreationInputTokens: max(ss.cacheWriteTokens, 0),
CacheReadInputTokens: max(ss.cacheReadTokens, 0),
ReasoningTokens: max(ss.reasoningTokens, 0),
CostUSD: cost,
CostStatus: ss.costStatus,
CostSource: ss.costSource,
OccurredAt: timeString(ss.endedAt, ss.startedAt),
DedupKey: "session:" + sessionID,
}}
}
func convertHermesStateMessages(
stateMessages []hermesStateMessage,
) []ParsedMessage {
msgs := make([]ParsedMessage, 0, len(stateMessages))
for _, hm := range stateMessages {
ordinal := len(msgs)
switch hm.role {
case "user":
content := strings.TrimSpace(hm.content)
if content == "" {
continue
}
display := stripHermesSkillPrefix(content)
isCompact := isHermesCompactBoundary(display)
msgs = append(msgs, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Content: display,
Timestamp: hm.timestamp,
ContentLength: len(content),
IsSystem: isCompact,
SourceType: sourceTypeIf(isCompact, "system"),
SourceSubtype: sourceTypeIf(isCompact, "compact_boundary"),
IsCompactBoundary: isCompact,
})
case "assistant":
content := strings.TrimSpace(hm.content)
reasoning := firstNonEmptyHermes(
hm.reasoning, hm.reasoningContent,
hm.reasoningDetails, hm.codexReasoningItems,
)
display := content
hasThinking := reasoning != ""
if hasThinking {
display = "[Thinking]\n" + reasoning +
"\n[/Thinking]\n" + display
}
var toolCalls []ParsedToolCall
if gjson.Valid(hm.toolCalls) {
gjson.Parse(hm.toolCalls).ForEach(
func(_, tc gjson.Result) bool {
name := tc.Get("function.name").Str
if name == "" {
name = tc.Get("name").Str
}
if name != "" {
toolCalls = append(toolCalls, ParsedToolCall{
ToolUseID: tc.Get("id").Str,
ToolName: name,
Category: NormalizeToolCategory(name),
InputJSON: tc.Get("function.arguments").Str,
})
}
return true
},
)
}
if display == "" && len(toolCalls) == 0 {
continue
}
msgs = append(msgs, ParsedMessage{
Ordinal: ordinal,
Role: RoleAssistant,
Content: display,
Timestamp: hm.timestamp,
HasThinking: hasThinking,
HasToolUse: len(toolCalls) > 0,
ContentLength: len(content) + len(reasoning),
ToolCalls: toolCalls,
})
case "tool":
if hm.toolCallID == "" {
continue
}
quoted, _ := json.Marshal(hm.content)
msgs = append(msgs, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Timestamp: hm.timestamp,
ContentLength: len(hm.content),
ToolResults: []ParsedToolResult{{
ToolUseID: hm.toolCallID,
ContentRaw: string(quoted),
ContentLength: len(hm.content),
}},
})
}
}
return msgs
}
func hermesMessageQuality(msgs []ParsedMessage) int {
score := len(msgs) * 1000
for _, msg := range msgs {
score += len(msg.Content)
if len(msg.ToolCalls) > 0 {
score += 100
}
if msg.HasThinking {
score += 50
}
}
return score
}
func hermesStateQuality(msgs []hermesStateMessage) int {
score := len(msgs) * 1000
for _, msg := range msgs {
score += len(msg.content)
if msg.toolCalls != "" {
score += 100
}
if firstNonEmptyHermes(
msg.reasoning, msg.reasoningContent,
msg.reasoningDetails, msg.codexReasoningItems,
) != "" {
score += 50
}
}
return score
}
func hermesUnixTime(v float64) time.Time {
if v <= 0 {
return time.Time{}
}
sec, frac := math.Modf(v)
return time.Unix(int64(sec), int64(frac*1_000_000_000)).UTC()
}
func timeString(primary, fallback time.Time) string {
if !primary.IsZero() {
return primary.Format(time.RFC3339Nano)
}
if !fallback.IsZero() {
return fallback.Format(time.RFC3339Nano)
}
return ""
}
func countHermesUsers(msgs []ParsedMessage) int {
count := 0
for _, msg := range msgs {
if msg.Role == RoleUser && !msg.IsSystem &&
len(msg.ToolResults) == 0 && strings.TrimSpace(msg.Content) != "" {
count++