Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(hermes): retain usage and cost in store-backed shares (#968)

Divyam Talwar77e3f989d0c6
diff --git a/cli/beacon/internal/handoff/hermes.go b/cli/beacon/internal/handoff/hermes.go
index 3b3d7483..db3b7c59 100644
--- a/cli/beacon/internal/handoff/hermes.go
+++ b/cli/beacon/internal/handoff/hermes.go
@@ -106,8 +106,8 @@ func (s *hermesSource) Events(session Session) ([]schema.Event, error) {
if err != nil {
return nil, err
}
- // A nil cursor maps the whole session, as a first sync would.
- mapped, _ := hermessession.MapSession(h, messages, nil)
+ // A zero cursor includes session-total usage, as a first sync would.
+ mapped, _ := hermessession.MapSession(h, messages, &hermessession.Cursor{})
events := make([]schema.Event, 0, len(mapped))
for _, m := range mapped {
events = append(events, m.Event)
diff --git a/cli/beacon/internal/handoff/hermes_test.go b/cli/beacon/internal/handoff/hermes_test.go
index fba6e8fa..9f31ecff 100644
--- a/cli/beacon/internal/handoff/hermes_test.go
+++ b/cli/beacon/internal/handoff/hermes_test.go
@@ -10,7 +10,10 @@ import (
"testing"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
var hermesUpdated = time.Date(2026, 9, 24, 11, 0, 0, 0, time.UTC)
@@ -141,6 +144,99 @@ func TestHermesSessionBuildsABrief(t *testing.T) {
}
}
+func TestHermesSessionUsageInShares(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ actualCost float64
+ estimatedCost float64
+ wantCost float64
+ usage bool
+ }{
+ {"actual cost preferred", 0.125, 0.5, 0.125, true},
+ {"estimated cost fallback", 0, 0.5, 0.5, true},
+ {"zero usage", 0, 0, 0, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dirs, path := hermesFixture(t)
+ want := asymptoteobserve.TraceUsageV1{}
+ if tc.usage {
+ want = asymptoteobserve.TraceUsageV1{
+ InputTokens: 100, OutputTokens: 25, CacheReadInputTokens: 10,
+ CacheCreationInputTokens: 5, ReasoningOutputTokens: 3, CostUSD: tc.wantCost,
+ }
+ }
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = db.Exec(`UPDATE sessions SET input_tokens = ?, output_tokens = ?,
+ cache_read_tokens = ?, cache_write_tokens = ?, reasoning_tokens = ?,
+ actual_cost_usd = ?, estimated_cost_usd = ? WHERE id = '20260924_100000_aaaaaa'`,
+ want.InputTokens, want.OutputTokens, want.CacheReadInputTokens,
+ want.CacheCreationInputTokens, want.ReasoningOutputTokens, tc.actualCost, tc.estimatedCost)
+ closeErr := db.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if closeErr != nil {
+ t.Fatal(closeErr)
+ }
+
+ sources := DefaultSources(dirs)
+ session, err := Find(sources, HarnessHermes, "20260924_100000_aaaaaa")
+ if err != nil {
+ t.Fatal(err)
+ }
+ events, err := Events(sources, session)
+ if err != nil {
+ t.Fatal(err)
+ }
+ actions := map[string]int{}
+ for _, event := range events {
+ actions[event.Event.Action]++
+ }
+ wantUsageEvents := 0
+ if tc.usage {
+ wantUsageEvents = 1
+ }
+ if actions["token.usage"] != wantUsageEvents {
+ t.Fatalf("usage events = %d, want %d; actions = %v", actions["token.usage"], wantUsageEvents, actions)
+ }
+ for _, action := range []string{"session.started", "prompt.submitted", "agent.message", "session.ended"} {
+ if actions[action] != 1 {
+ t.Errorf("%s events = %d, want 1", action, actions[action])
+ }
+ }
+
+ bundle := asymptoteobserve.BuildShareBundle(events, asymptoteobserve.ShareOptions{GeneratedAt: hermesUpdated})
+ if tc.usage {
+ if !reflect.DeepEqual(bundle.Summary.TokenUsage, &want) {
+ t.Errorf("share usage = %+v, want %+v", bundle.Summary.TokenUsage, want)
+ }
+ } else if bundle.Summary.TokenUsage != nil {
+ t.Errorf("zero-usage share = %+v, want no usage", bundle.Summary.TokenUsage)
+ }
+ // The share command uses these aggregate totals instead of the bundle's plain sum.
+ totals := tokens.Aggregate(events, tokens.Options{}).Totals
+ got := asymptoteobserve.TraceUsageV1{
+ InputTokens: totals.InputTokens, OutputTokens: totals.OutputTokens,
+ CacheReadInputTokens: totals.CacheReadInputTokens, CacheCreationInputTokens: totals.CacheCreationInputTokens,
+ ReasoningOutputTokens: totals.ReasoningOutputTokens, CostUSD: totals.CostUSD,
+ }
+ if got != want {
+ t.Errorf("aggregated share usage = %+v, want %+v", got, want)
+ }
+ again, err := Events(sources, session)
+ if err != nil || !reflect.DeepEqual(again, events) {
+ t.Errorf("repeated read changed events or identities: err=%v", err)
+ }
+ if _, err := os.Stat(filepath.Dir(hermessession.DefaultStatePath())); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("reading a session created collection state: %v", err)
+ }
+ })
+ }
+}
+
func TestHermesSessionGoneFromItsStore(t *testing.T) {
dirs, path := hermesFixture(t)
sources := DefaultSources(dirs)
diff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.go
index 63979024..cce8e9ce 100644
--- a/cli/beacon/internal/hermessession/collect.go
+++ b/cli/beacon/internal/hermessession/collect.go
@@ -554,14 +554,15 @@ func openSQLiteReadOnly(path string) (*sql.DB, error) {
// The pending calls are returned rather than written onto the cursor so the caller can persist them
// only once every event in the batch is written. Recording them earlier would drop a call's
// arguments when a later emit fails and the sweep retries the same messages.
+//
+// cursor is what earlier sweeps collected; a zero Cursor maps the whole session, session-total
+// usage included, as a first sync does.
func MapSession(session Session, messages []Message, cursor *Cursor) ([]MappedEvent, map[string]json.RawMessage) {
m := &mapper{session: session, cursor: cursor, calls: map[string]toolCall{}}
- if cursor != nil {
- for id, raw := range cursor.PendingCalls {
- var call toolCall
- if json.Unmarshal(raw, &call) == nil && call.ID != "" {
- m.calls[id] = call
- }
+ for id, raw := range cursor.PendingCalls {
+ var call toolCall
+ if json.Unmarshal(raw, &call) == nil && call.ID != "" {
+ m.calls[id] = call
}
}
m.mapSession()
@@ -606,7 +607,7 @@ type toolCall struct {
}
func (m *mapper) mapSession() {
- if m.cursor != nil && m.cursor.Started {
+ if m.cursor.Started {
return
}
ev := m.base(m.session.StartedAtMS, "session.started", "session", schema.SeverityInfo, "Hermes session started")
@@ -619,7 +620,7 @@ func (m *mapper) mapSession() {
}
func (m *mapper) mapSessionEnd() {
- if m.session.EndedAtMS == 0 || (m.cursor != nil && m.cursor.EndedAtMS == m.session.EndedAtMS) {
+ if m.session.EndedAtMS == 0 || m.cursor.EndedAtMS == m.session.EndedAtMS {
return
}
ev := m.base(m.session.EndedAtMS, "session.ended", "session", schema.SeverityInfo, "Hermes session ended")
@@ -630,9 +631,6 @@ func (m *mapper) mapSessionEnd() {
}
func (m *mapper) mapUsage() {
- if m.cursor == nil {
- return
- }
usage := &schema.GenAIUsageInfo{}
if delta := m.session.InputTokens - m.cursor.InputTokens; delta > 0 {
usage.InputTokens = &delta
diff --git a/cli/beacon/internal/hermessession/handoff_test.go b/cli/beacon/internal/hermessession/handoff_test.go
index 252f55a6..d7f1eeba 100644
--- a/cli/beacon/internal/hermessession/handoff_test.go
+++ b/cli/beacon/internal/hermessession/handoff_test.go
@@ -15,7 +15,7 @@ func TestMapSessionRecordsAHandoffLink(t *testing.T) {
{ID: 2, SessionID: "new-1", Role: "assistant", Content: "Reading the brief.", TimestampMS: 1780632832000, Active: true},
{ID: 3, SessionID: "new-1", Role: "user", Content: "no marker here", TimestampMS: 1780632833000, Active: true},
}
- mapped, _ := MapSession(session, messages, nil)
+ mapped, _ := MapSession(session, messages, &Cursor{})
var links []MappedEvent
for _, m := range mapped {
if m.Event.Event.Action == "session.handoff" {
@@ -45,7 +45,7 @@ func TestMapSessionRecordsAHandoffLink(t *testing.T) {
}
ids[m.Event.Event.ID] = true
}
- again, _ := MapSession(session, messages, nil)
+ again, _ := MapSession(session, messages, &Cursor{})
for i := range mapped {
if again[i].Event.Event.ID != mapped[i].Event.Event.ID {
t.Fatal("event ids must be deterministic, so a second sync never duplicates the link")
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index fcbbbd42..835f09da 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -15,6 +15,7 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
- **Claude.ai and ChatGPT answers show in traces** · Answers the browser extension records as `agent.response.completed` were classified as `other` in trace views, so `beacon endpoint traces show`, the dashboard and shared traces showed the prompt without the answer. They are now assistant messages carrying the answer, as are plans recorded as `agent.plan`. OpenCode's separate completion event, which carries only usage, stays out of the conversation. Local history is rebuilt on its next read, so earlier sessions show their answers too.
- **Lens findings link to events without an ID** · When a session's events carried no `event.id`, as events written through the SDK's `JSONLSink` or by releases before late August do, a lens finding on one of them came back with empty `event_ids`, so its evidence link pointed nowhere. Findings now name the same `line-N` identifier the trace shows for that event, and an explicit ID containing whitespace is no longer trimmed out of matching it.
- **Session lenses show when a share is out of date** · A lens opened on a dashboard session page reported a shared session as `shared` after new work, while the trace lens and the session details showed it as stale, and it gave no refresh command. Session lenses now apply the same sharing state as the rest of the dashboard, including the `beacon share refresh` command.
+- **Shared Hermes sessions keep their token usage and cost** · `beacon share` of a Hermes Agent session read from its `state.db` left out the session's token usage and cost, so the shared trace showed none. They are now included, with Hermes's actual cost preferred over its estimate, as `beacon endpoint hermes sync` records them.
- **Dashboard output tokens count reasoning once** · The local dashboard's token view added reasoning tokens to output, but `gen_ai.usage.output_tokens` already includes them, so models that report reasoning had their output and total tokens overstated. Output and the total now count reasoning once, the split bar no longer shows reasoning as a separate segment, and a note below it gives the reasoning count included in output. `beacon token-usage` already counted it this way.
---