Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix: attribute Hermes usage to current model (MUL-2696)

Multica Eve26ff52385b88
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index 2ef2820abb..456bdbd36d 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -191,6 +191,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
finalStatus := "completed"
var finalError string
var sessionID string
+ effectiveModel := strings.TrimSpace(opts.Model)
// 1. Initialize handshake.
_, err := c.request(runCtx, "initialize", map[string]any{
@@ -234,6 +235,9 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
"actual", sessionID,
)
}
+ if effectiveModel == "" {
+ effectiveModel = extractACPCurrentModelID(result)
+ }
} else {
result, err := c.request(runCtx, "session/new", buildHermesSessionParams(cwd, opts.Model))
if err != nil {
@@ -249,6 +253,9 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
return
}
+ if effectiveModel == "" {
+ effectiveModel = extractACPCurrentModelID(result)
+ }
}
c.sessionID = sessionID
@@ -324,6 +331,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
c.usageMu.Lock()
c.usage.InputTokens += pr.usage.InputTokens
c.usage.OutputTokens += pr.usage.OutputTokens
+ c.usage.CacheReadTokens += pr.usage.CacheReadTokens
c.usageMu.Unlock()
default:
}
@@ -367,7 +375,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
var usageMap map[string]TokenUsage
if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 {
- model := opts.Model
+ model := effectiveModel
if model == "" {
model = "unknown"
}
@@ -1135,6 +1143,35 @@ func extractACPSessionID(result json.RawMessage) string {
return r.SessionID
}
+// extractACPCurrentModelID pulls the model selected by the ACP runtime out of
+// a session/new or session/resume response. Hermes returns this when it uses
+// its own default model, so token usage can still be attributed to a real model
+// even when Multica did not pass an explicit agent.model override.
+func extractACPCurrentModelID(result json.RawMessage) string {
+ var r struct {
+ Models struct {
+ CurrentModelID string `json:"currentModelId"`
+ CurrentModelIDSnake string `json:"current_model_id"`
+ } `json:"models"`
+ CurrentModelID string `json:"currentModelId"`
+ CurrentModelIDSnake string `json:"current_model_id"`
+ }
+ if err := json.Unmarshal(result, &r); err != nil {
+ return ""
+ }
+ for _, candidate := range []string{
+ r.Models.CurrentModelID,
+ r.Models.CurrentModelIDSnake,
+ r.CurrentModelID,
+ r.CurrentModelIDSnake,
+ } {
+ if model := strings.TrimSpace(candidate); model != "" {
+ return model
+ }
+ }
+ return ""
+}
+
// resolveResumedSessionID picks which session id we should treat as live
// after a `session/resume` round-trip. Hermes (and other ACP servers)
// return the canonical sessionId in the response — when the local
diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.go
index 810040f66b..5af2fbd7ff 100644
--- a/server/pkg/agent/hermes_test.go
+++ b/server/pkg/agent/hermes_test.go
@@ -51,6 +51,43 @@ func TestExtractACPSessionIDInvalidJSON(t *testing.T) {
}
}
+// ── extractACPCurrentModelID ──
+
+func TestExtractACPCurrentModelID(t *testing.T) {
+ t.Parallel()
+ raw := json.RawMessage(`{
+ "sessionId": "ses_123",
+ "models": {
+ "currentModelId": "nous:moonshotai/kimi-k2.6"
+ }
+ }`)
+ got := extractACPCurrentModelID(raw)
+ if got != "nous:moonshotai/kimi-k2.6" {
+ t.Errorf("got %q, want current model", got)
+ }
+}
+
+func TestExtractACPCurrentModelIDSnakeCase(t *testing.T) {
+ t.Parallel()
+ raw := json.RawMessage(`{
+ "session_id": "ses_123",
+ "models": {
+ "current_model_id": "openrouter:anthropic/claude-sonnet-4.6"
+ }
+ }`)
+ got := extractACPCurrentModelID(raw)
+ if got != "openrouter:anthropic/claude-sonnet-4.6" {
+ t.Errorf("got %q, want current model", got)
+ }
+}
+
+func TestExtractACPCurrentModelIDMissing(t *testing.T) {
+ t.Parallel()
+ if got := extractACPCurrentModelID(json.RawMessage(`{"sessionId":"ses_123"}`)); got != "" {
+ t.Errorf("got %q, want empty", got)
+ }
+}
+
// ── resolveResumedSessionID ──
func TestResolveResumedSessionIDMatching(t *testing.T) {
@@ -1039,6 +1076,74 @@ func TestHermesProviderErrorSnifferBoundedBuffer(t *testing.T) {
}
}
+func fakeHermesACPUsageWithDefaultModelScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_model","models":{"currentModelId":"nous:moonshotai/kimi-k2.6","availableModels":[{"modelId":"nous:moonshotai/kimi-k2.6","name":"moonshotai/kimi-k2.6"}]}}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3}}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+func TestHermesBackendAttributesUsageToACPDefaultModel(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "hermes")
+ writeTestExecutable(t, fakePath, []byte(fakeHermesACPUsageWithDefaultModelScript()))
+
+ backend, err := New("hermes", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new hermes backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "completed" {
+ t.Fatalf("expected completed result, got %q: %s", result.Status, result.Error)
+ }
+ if _, ok := result.Usage["unknown"]; ok {
+ t.Fatalf("usage should not be attributed to unknown: %+v", result.Usage)
+ }
+ usage, ok := result.Usage["nous:moonshotai/kimi-k2.6"]
+ if !ok {
+ t.Fatalf("expected usage under Hermes current model, got %+v", result.Usage)
+ }
+ if usage.InputTokens != 17 || usage.OutputTokens != 5 || usage.CacheReadTokens != 3 {
+ t.Fatalf("usage = %+v, want input=17 output=5 cache_read=3", usage)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
// fakeHermesACPRateLimitScript impersonates hermes for the GitHub
// multica#1952 scenario: the upstream LLM returns HTTP 429 (rate
// limited / no credit), hermes retries internally and ultimately
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 1992cc1cf2..24d00d19b2 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -697,44 +697,65 @@ func discoverACPModels(ctx context.Context, executablePath string, p acpDiscover
// the caller can distinguish "parsed with no models" (valid but
// empty catalog) from "couldn't find the structure at all".
func parseACPSessionNewModels(raw json.RawMessage) []Model {
+ type acpModelInfo struct {
+ ModelID string `json:"modelId"`
+ ModelIDSnake string `json:"model_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ }
var resp struct {
Models struct {
- AvailableModels []struct {
- ModelID string `json:"modelId"`
- Name string `json:"name"`
- Description string `json:"description"`
- } `json:"availableModels"`
- CurrentModelID string `json:"currentModelId"`
+ AvailableModels []acpModelInfo `json:"availableModels"`
+ AvailableModelsSnake []acpModelInfo `json:"available_models"`
+ CurrentModelID string `json:"currentModelId"`
+ CurrentModelIDSnake string `json:"current_model_id"`
} `json:"models"`
}
if err := json.Unmarshal(raw, &resp); err != nil {
return nil
}
- models := make([]Model, 0, len(resp.Models.AvailableModels))
+ availableModels := resp.Models.AvailableModels
+ if len(availableModels) == 0 && resp.Models.AvailableModelsSnake != nil {
+ availableModels = resp.Models.AvailableModelsSnake
+ }
+ currentModelID := strings.TrimSpace(resp.Models.CurrentModelID)
+ if currentModelID == "" {
+ currentModelID = strings.TrimSpace(resp.Models.CurrentModelIDSnake)
+ }
+ models := make([]Model, 0, len(availableModels))
seen := map[string]bool{}
- for _, m := range resp.Models.AvailableModels {
- if m.ModelID == "" || seen[m.ModelID] {
- continue
+ for _, m := range availableModels {
+ modelID := strings.TrimSpace(m.ModelID)
+ if modelID == "" {
+ modelID = strings.TrimSpace(m.ModelIDSnake)
}
- seen[m.ModelID] = true
- label := m.Name
- if label == "" {
- label = m.ModelID
+ if modelID == "" || seen[modelID] {
+ continue
}
+ seen[modelID] = true
+ label := acpModelLabel(m.Name, modelID)
provider := ""
- if idx := strings.Index(m.ModelID, ":"); idx > 0 {
- provider = m.ModelID[:idx]
+ if idx := strings.Index(modelID, ":"); idx > 0 {
+ provider = modelID[:idx]
}
models = append(models, Model{
- ID: m.ModelID,
+ ID: modelID,
Label: label,
Provider: provider,
- Default: m.ModelID == resp.Models.CurrentModelID,
+ Default: modelID == currentModelID,
})
}
return models
}
+func acpModelLabel(name, modelID string) string {
+ label := strings.TrimSpace(name)
+ if label == "" || strings.EqualFold(label, "unknown") {
+ return modelID
+ }
+ return label
+}
+
// discoverCursorModels runs `cursor-agent --list-models` and parses
// the `id - Label` rows. Cursor's catalog changes often and ships
// many variants of the same base model (thinking / fast / max
diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.go
index d3a64852d0..a5e53ca3d9 100644
--- a/server/pkg/agent/models_test.go
+++ b/server/pkg/agent/models_test.go
@@ -144,9 +144,9 @@ func TestInferCopilotProvider(t *testing.T) {
"raptor-mini": "",
// negative cases: must not be misidentified as OpenAI
// reasoning series even though they start with `o`.
- "opus-fake": "",
- "omni": "",
- "o": "",
+ "opus-fake": "",
+ "omni": "",
+ "o": "",
}
for id, want := range cases {
if got := inferCopilotProvider(id); got != want {
@@ -511,6 +511,32 @@ func TestParseHermesSessionNewModels(t *testing.T) {
}
}
+func TestParseHermesSessionNewModelsSnakeCaseAndUnknownNames(t *testing.T) {
+ raw := []byte(`{
+ "session_id": "ses_123",
+ "models": {
+ "available_models": [
+ {"model_id": "nous:moonshotai/kimi-k2.6", "name": "Unknown", "description": "Provider: Nous"},
+ {"model_id": "nous:anthropic/claude-sonnet-4.6", "name": "unknown", "description": "Provider: Nous"}
+ ],
+ "current_model_id": "nous:moonshotai/kimi-k2.6"
+ }
+ }`)
+ models := parseACPSessionNewModels(raw)
+ if len(models) != 2 {
+ t.Fatalf("expected 2 models, got %d: %+v", len(models), models)
+ }
+ if models[0].Label != "nous:moonshotai/kimi-k2.6" {
+ t.Errorf("Unknown label should fall back to model id, got %+v", models[0])
+ }
+ if !models[0].Default {
+ t.Errorf("snake_case current_model_id should mark default: %+v", models[0])
+ }
+ if models[1].Label != "nous:anthropic/claude-sonnet-4.6" {
+ t.Errorf("lowercase unknown label should fall back to model id, got %+v", models[1])
+ }
+}
+
func TestParseHermesSessionNewModelsMissingField(t *testing.T) {
// session/new without the models field — older hermes or
// failed _build_model_state — should yield nil so the caller