Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agent): add Hermes Agent Provider via ACP protocol (#623)
LinYushena25886102aab
diff --git a/packages/views/agents/components/create-agent-dialog.tsx b/packages/views/agents/components/create-agent-dialog.tsxindex 1ea3d80cee..4abb48e737 100644--- a/packages/views/agents/components/create-agent-dialog.tsx+++ b/packages/views/agents/components/create-agent-dialog.tsx@@ -1,14 +1,8 @@"use client";import { useState, useEffect } from "react";-import {- Cloud,- Monitor,- ChevronDown,- Globe,- Lock,- Loader2,-} from "lucide-react";+import { Cloud, ChevronDown, Globe, Lock, Loader2 } from "lucide-react";+import { ProviderLogo } from "../../runtimes/components/provider-logo";import type {AgentVisibility,RuntimeDevice,@@ -85,7 +79,7 @@ export function CreateAgentDialog({</DialogDescription></DialogHeader>- <div className="space-y-4">+ <div className="space-y-4 min-w-0"><div><Label className="text-xs text-muted-foreground">Name</Label><Input@@ -146,19 +140,19 @@ export function CreateAgentDialog({</div></div>- <div>+ <div className="min-w-0"><Label className="text-xs text-muted-foreground">Runtime</Label><Popover open={runtimeOpen} onOpenChange={setRuntimeOpen}><PopoverTriggerdisabled={runtimes.length === 0 && !runtimesLoading}- className="flex w-full items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 mt-1.5 text-left text-sm transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-50"+ className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 mt-1.5 text-left text-sm transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-50">{runtimesLoading ? (<Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" />- ) : selectedRuntime?.runtime_mode === "cloud" ? (- <Cloud className="h-4 w-4 shrink-0 text-muted-foreground" />+ ) : selectedRuntime ? (+ <ProviderLogo provider={selectedRuntime.provider} className="h-4 w-4 shrink-0" />) : (- <Monitor className="h-4 w-4 shrink-0 text-muted-foreground" />+ <Cloud className="h-4 w-4 shrink-0 text-muted-foreground" />)}<div className="min-w-0 flex-1"><div className="flex items-center gap-2">@@ -189,11 +183,7 @@ export function CreateAgentDialog({device.id === selectedRuntimeId ? "bg-accent" : "hover:bg-accent/50"}`}>- {device.runtime_mode === "cloud" ? (- <Cloud className="h-4 w-4 shrink-0 text-muted-foreground" />- ) : (- <Monitor className="h-4 w-4 shrink-0 text-muted-foreground" />- )}+ <ProviderLogo provider={device.provider} className="h-4 w-4 shrink-0" /><div className="min-w-0 flex-1"><div className="flex items-center gap-2"><span className="truncate font-medium">{device.name}</span>diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsxindex 8357ef2da0..c184350168 100644--- a/packages/views/runtimes/components/provider-logo.tsx+++ b/packages/views/runtimes/components/provider-logo.tsx@@ -28,67 +28,51 @@ function OpenCodeLogo({ className }: { className: string }) {);}-// OpenClaw — official pixel lobster mascot from openclaw/openclaw+// OpenClaw — lobster mascot, vector version based on official brandingfunction OpenClawLogo({ className }: { className: string }) {return (<svg viewBox="0 0 16 16" fill="none" className={className}>- {/* outline */}- <g fill="#3a0a0d">- <rect x="1" y="5" width="1" height="3" />- <rect x="2" y="4" width="1" height="1" />- <rect x="2" y="8" width="1" height="1" />- <rect x="3" y="3" width="1" height="1" />- <rect x="3" y="9" width="1" height="1" />- <rect x="4" y="2" width="1" height="1" />- <rect x="4" y="10" width="1" height="1" />- <rect x="5" y="2" width="6" height="1" />- <rect x="11" y="2" width="1" height="1" />- <rect x="12" y="3" width="1" height="1" />- <rect x="12" y="9" width="1" height="1" />- <rect x="13" y="4" width="1" height="1" />- <rect x="13" y="8" width="1" height="1" />- <rect x="14" y="5" width="1" height="3" />- <rect x="5" y="11" width="6" height="1" />- <rect x="4" y="12" width="1" height="1" />- <rect x="11" y="12" width="1" height="1" />- <rect x="3" y="13" width="1" height="1" />- <rect x="12" y="13" width="1" height="1" />- <rect x="5" y="14" width="6" height="1" />- </g>- {/* body */}- <g fill="#ff4f40">- <rect x="5" y="3" width="6" height="1" />- <rect x="4" y="4" width="8" height="1" />- <rect x="3" y="5" width="10" height="1" />- <rect x="3" y="6" width="10" height="1" />- <rect x="3" y="7" width="10" height="1" />- <rect x="4" y="8" width="8" height="1" />- <rect x="5" y="9" width="6" height="1" />- <rect x="5" y="12" width="6" height="1" />- <rect x="6" y="13" width="4" height="1" />- </g>- {/* claws */}- <g fill="#ff775f">- <rect x="1" y="6" width="2" height="1" />- <rect x="2" y="5" width="1" height="1" />- <rect x="2" y="7" width="1" height="1" />- <rect x="13" y="6" width="2" height="1" />- <rect x="13" y="5" width="1" height="1" />- <rect x="13" y="7" width="1" height="1" />- </g>- {/* eyes */}- <g fill="#081016">- <rect x="6" y="5" width="1" height="1" />- <rect x="9" y="5" width="1" height="1" />- </g>- <g fill="#f5fbff">- <rect x="6" y="4" width="1" height="1" />- <rect x="9" y="4" width="1" height="1" />- </g>+ {/* Body */}+ <path+ d="M8 2C5.5 2 3.5 4 3.5 6.5S5 10.5 6.5 11v1.5H8V11c.3.1.7.1 1 0v1.5h1.5V11c1.5-.5 3-2.5 3-4.5S10.5 2 8 2Z"+ fill="#E8453A"+ />+ {/* Left claw */}+ <path+ d="M3.5 5.5C2 5 1 6 1.5 7s2 .5 2.2-.7"+ fill="#FF6B5A"+ />+ {/* Right claw */}+ <path+ d="M12.5 5.5c1.5-.5 2.5.5 2 1.5s-2 .5-2.2-.7"+ fill="#FF6B5A"+ />+ {/* Antennae */}+ <path d="M6.5 3Q5 1.2 4.3 1.5" stroke="#FF6B5A" strokeWidth="0.8" strokeLinecap="round" />+ <path d="M9.5 3Q11 1.2 11.7 1.5" stroke="#FF6B5A" strokeWidth="0.8" strokeLinecap="round" />+ {/* Eyes */}+ <circle cx="6.2" cy="5.2" r="0.9" fill="#050810" />+ <circle cx="9.8" cy="5.2" r="0.9" fill="#050810" />+ <circle cx="6.4" cy="5" r="0.3" fill="#00E5CC" />+ <circle cx="10" cy="5" r="0.3" fill="#00E5CC" /></svg>);}+// Hermes (NousResearch) — official anime mascot, 48×48 webp embedded as data URI+const HERMES_ICON =+ "data:image/webp;base64,UklGRuYDAABXRUJQVlA4INoDAADQEwCdASowADAAPm0uk0ckIiGhKrqpWIANiWkAEyQea/fD8IewvGL5V7Nb3H8u/MA8G9rT+4flL+UfIe42/23GB8zPqF/o3E0UAP5h/h/+F6ZX+x5evnX/r+4T/K/67/u/zg7znogfrusMANZLkn1gvlY/vNsKubtj/9xLSzxTsLr7K9GLdFNs5rwtISRcPXvH4z57n2fg0XR3aQ2D+pPpycwyl7TwAAD+/2DbjivnePzfyHCsdOgJXKlUR/OgAkofD7K4AdmsPKyP5Ml4/4HBYmIm5/efn/H+X3IZtngyaUOvwbFuRS/1yODFYO3vf3qeXGgPdfgIROXd/EPT7K2jysfvY9N71+w6g2gBPs+P6lxYkPf6S9QfpvH/7Pp7i8xRh0nVDBTEQyczSz7V9hoqo4nDJuii+SfibZRR/d5zB+9jkcb1DNN7YnC5Y7+WfGrE3eseXt3hSm+NS5++m1MHbjsrd9z/Q4HPRP/C85Po41XObalGyIUcFUL2j2n3uI/Yh6U8r6trCUJFB4kT3fsv6+8ylX/d96y2hq869FCXLjq4YqEO8vs5BtT52sf7KyDxPAWkH/b06YbfVXf4/7y5THL6Sr/4mOrrY9P2LW81f05HHFN8n0jcyqKOH7AluMm0AHPgFyz8RVrfBdmnPiC2FLMQfNDte5yGFzGC3fMlDed/tS/PO3Q/hjsNLvAXUUjqHyCo3JeN69jyNgWjjf8iUqoBsXT+lJyp2r8p60ad1jxhNyTblyJwda8aWEw1hFDeGjpMGguDF66RL4c+ZO+PhculC6WxvCsZ7IPAsdD7/ywx3w3AowJ66hAAK7k+m6X2QV06OVOCwyIGERex/AUyuBbLUK93X58+M+Si7YfYjVYGpoJ7JvSgD8ExaA21z9OY+si+1wreacDanKnFDmhwBQC3t6MLeXCOGp3VURDKl10K7tdKHQcb4hr48ba+1x/MrMRwHfq3IQrDIXPYCg4b0OLnVN9JyXttKGM63B5imIdKuU0r6hhSslT10lGLjnIJuwO5WKR0RHs+BX5vs6H63y3K7IuuZ1eRN+Aczvbs4QuDs6ZRuzjJ/1DJ5R/3ZrFPrtxvMwT06vAXIgcbhLGNLhOQUYRPdUN5MgyCtL5NH71ArTPLRRkIjhGwoCYXKKqlqIKKT9NX3vwp/nlh4SX71dlYg/mPXbJ9bMeVugyjqFahjFTJ/rT3HtBCWG8h+OvvbOFDFKurCG9BOhO9B719OS7zsP0KPqoymnv7hVvoJyZp0iziCbBvaJpmF9Cvfs8/vWqWr7TUo616WfMW+X9nkgpuqtnfAAAAAA==";++function HermesLogo({ className }: { className: string }) {+ return (+ <img+ src={HERMES_ICON}+ alt="Hermes"+ className={`${className} rounded-sm`}+ />+ );+}+export function ProviderLogo({provider,className = "h-4 w-4",@@ -105,6 +89,8 @@ export function ProviderLogo({return <OpenCodeLogo className={className} />;case "openclaw":return <OpenClawLogo className={className} />;+ case "hermes":+ return <HermesLogo className={className} />;default:return <Monitor className={className} />;}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 896c7f1731..fc0fcad7bd 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -30,7 +30,7 @@ type Config struct {RuntimeName stringCLIVersion string // multica CLI version (e.g. "0.1.13")Profile string // profile name (empty = default)- Agents map[string]AgentEntry // "claude" -> entry, "codex" -> entry, "opencode" -> entry, "openclaw" -> entry+ Agents map[string]AgentEntry // "claude" -> entry, "codex" -> entry, "opencode" -> entry, "openclaw" -> entry, "hermes" -> entryWorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)KeepEnvAfterTask bool // preserve env after task for debuggingHealthPort int // local HTTP port for health checks (default: 19514)@@ -99,8 +99,15 @@ func LoadConfig(overrides Overrides) (Config, error) {Model: strings.TrimSpace(os.Getenv("MULTICA_OPENCLAW_MODEL")),}}+ hermesPath := envOrDefault("MULTICA_HERMES_PATH", "hermes")+ if _, err := exec.LookPath(hermesPath); err == nil {+ agents["hermes"] = AgentEntry{+ Path: hermesPath,+ Model: strings.TrimSpace(os.Getenv("MULTICA_HERMES_MODEL")),+ }+ }if len(agents) == 0 {- return Config{}, fmt.Errorf("no agent CLI found: install claude, codex, opencode, or openclaw and ensure it is on PATH")+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codex, opencode, openclaw, or hermes and ensure it is on PATH")}// Host infodiff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 08ab57f7c7..2d7c347c50 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -1,5 +1,5 @@// Package agent provides a unified interface for executing prompts via-// coding agents (Claude Code, Codex, OpenCode, OpenClaw). It mirrors the happy-cli AgentBackend+// coding agents (Claude Code, Codex, OpenCode, OpenClaw, Hermes). It mirrors the happy-cli AgentBackend// pattern, translated to idiomatic Go.package agent@@ -82,13 +82,13 @@ type Result struct {// Config configures a Backend instance.type Config struct {- ExecutablePath string // path to CLI binary (claude, codex, opencode, or openclaw)+ ExecutablePath string // path to CLI binary (claude, codex, opencode, openclaw, or hermes)Env map[string]string // extra environment variablesLogger *slog.Logger}// New creates a Backend for the given agent type.-// Supported types: "claude", "codex", "opencode", "openclaw".+// Supported types: "claude", "codex", "opencode", "openclaw", "hermes".func New(agentType string, cfg Config) (Backend, error) {if cfg.Logger == nil {cfg.Logger = slog.Default()@@ -103,8 +103,10 @@ func New(agentType string, cfg Config) (Backend, error) {return &opencodeBackend{cfg: cfg}, nilcase "openclaw":return &openclawBackend{cfg: cfg}, nil+ case "hermes":+ return &hermesBackend{cfg: cfg}, nildefault:- return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codex, opencode, openclaw)", agentType)+ return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codex, opencode, openclaw, hermes)", agentType)}}diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.gonew file mode 100644index 0000000000..244d5799a0--- /dev/null+++ b/server/pkg/agent/hermes.go@@ -0,0 +1,641 @@+package agent++import (+ "bufio"+ "context"+ "encoding/json"+ "fmt"+ "os/exec"+ "strings"+ "sync"+ "time"+)++// hermesBackend implements Backend by spawning `hermes acp` and communicating+// via the ACP (Agent Communication Protocol) JSON-RPC 2.0 over stdin/stdout.+// This is the same pattern as Codex but with the ACP protocol instead of+// the Codex-specific JSON-RPC methods.+type hermesBackend struct {+ cfg Config+}++func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ execPath := b.cfg.ExecutablePath+ if execPath == "" {+ execPath = "hermes"+ }+ if _, err := exec.LookPath(execPath); err != nil {+ return nil, fmt.Errorf("hermes executable not found at %q: %w", execPath, err)+ }++ timeout := opts.Timeout+ if timeout == 0 {+ timeout = 20 * time.Minute+ }+ runCtx, cancel := context.WithTimeout(ctx, timeout)++ cmd := exec.CommandContext(runCtx, execPath, "acp")+ if opts.Cwd != "" {+ cmd.Dir = opts.Cwd+ }++ env := buildEnv(b.cfg.Env)+ // Enable yolo mode so Hermes auto-approves all tool executions.+ env = append(env, "HERMES_YOLO_MODE=1")+ cmd.Env = env++ stdout, err := cmd.StdoutPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("hermes stdout pipe: %w", err)+ }+ stdin, err := cmd.StdinPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("hermes stdin pipe: %w", err)+ }+ cmd.Stderr = newLogWriter(b.cfg.Logger, "[hermes:stderr] ")++ if err := cmd.Start(); err != nil {+ cancel()+ return nil, fmt.Errorf("start hermes: %w", err)+ }++ b.cfg.Logger.Info("hermes acp started", "pid", cmd.Process.Pid, "cwd", opts.Cwd)++ msgCh := make(chan Message, 256)+ resCh := make(chan Result, 1)++ var outputMu sync.Mutex+ var output strings.Builder++ promptDone := make(chan hermesPromptResult, 1)++ c := &hermesClient{+ cfg: b.cfg,+ stdin: stdin,+ pending: make(map[int]*pendingRPC),+ onMessage: func(msg Message) {+ if msg.Type == MessageText {+ outputMu.Lock()+ output.WriteString(msg.Content)+ outputMu.Unlock()+ }+ trySend(msgCh, msg)+ },+ onPromptDone: func(result hermesPromptResult) {+ select {+ case promptDone <- result:+ default:+ }+ },+ }++ // Start reading stdout in background.+ readerDone := make(chan struct{})+ go func() {+ defer close(readerDone)+ scanner := bufio.NewScanner(stdout)+ scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ c.handleLine(line)+ }+ c.closeAllPending(fmt.Errorf("hermes process exited"))+ }()++ // Drive the ACP session lifecycle in a goroutine.+ go func() {+ defer cancel()+ defer close(msgCh)+ defer close(resCh)+ defer func() {+ stdin.Close()+ _ = cmd.Wait()+ }()++ startTime := time.Now()+ finalStatus := "completed"+ var finalError string+ var sessionID string++ // 1. Initialize handshake.+ _, err := c.request(runCtx, "initialize", map[string]any{+ "protocolVersion": 1,+ "clientInfo": map[string]any{+ "name": "multica-agent-sdk",+ "version": "0.2.0",+ },+ "clientCapabilities": map[string]any{},+ })+ if err != nil {+ finalStatus = "failed"+ finalError = fmt.Sprintf("hermes initialize failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }++ // 2. Create or resume a session.+ cwd := opts.Cwd+ if cwd == "" {+ cwd = "."+ }++ if opts.ResumeSessionID != "" {+ result, err := c.request(runCtx, "session/resume", map[string]any{+ "cwd": cwd,+ "sessionId": opts.ResumeSessionID,+ })+ if err != nil {+ finalStatus = "failed"+ finalError = fmt.Sprintf("hermes session/resume failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ sessionID = opts.ResumeSessionID+ _ = result+ } else {+ result, err := c.request(runCtx, "session/new", map[string]any{+ "cwd": cwd,+ "mcpServers": []any{},+ })+ if err != nil {+ finalStatus = "failed"+ finalError = fmt.Sprintf("hermes session/new failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ sessionID = extractHermesSessionID(result)+ if sessionID == "" {+ finalStatus = "failed"+ finalError = "hermes session/new returned no session ID"+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ }++ c.sessionID = sessionID+ b.cfg.Logger.Info("hermes session created", "session_id", sessionID)++ // 3. Build the prompt content. If we have a system prompt, prepend it.+ userText := prompt+ if opts.SystemPrompt != "" {+ userText = opts.SystemPrompt + "\n\n---\n\n" + prompt+ }++ // 4. Send the prompt and wait for PromptResponse.+ _, err = c.request(runCtx, "session/prompt", map[string]any{+ "sessionId": sessionID,+ "prompt": []map[string]any{+ {"type": "text", "text": userText},+ },+ })+ if err != nil {+ // If the request itself failed (not just context cancelled),+ // check if the context was cancelled/timed out.+ if runCtx.Err() == context.DeadlineExceeded {+ finalStatus = "timeout"+ finalError = fmt.Sprintf("hermes timed out after %s", timeout)+ } else if runCtx.Err() == context.Canceled {+ finalStatus = "aborted"+ finalError = "execution cancelled"+ } else {+ finalStatus = "failed"+ finalError = fmt.Sprintf("hermes session/prompt failed: %v", err)+ }+ } else {+ // The prompt completed. Check if we got a promptDone result+ // from the response parsing.+ select {+ case pr := <-promptDone:+ if pr.stopReason == "cancelled" {+ finalStatus = "aborted"+ finalError = "hermes cancelled the prompt"+ }+ // Merge usage from the PromptResponse.+ c.usageMu.Lock()+ c.usage.InputTokens += pr.usage.InputTokens+ c.usage.OutputTokens += pr.usage.OutputTokens+ c.usageMu.Unlock()+ default:+ }+ }++ duration := time.Since(startTime)+ b.cfg.Logger.Info("hermes finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())++ // Close stdin and cancel context to signal hermes acp to exit.+ stdin.Close()+ cancel()++ // Wait for the reader goroutine to finish so all output is accumulated.+ <-readerDone++ outputMu.Lock()+ finalOutput := output.String()+ outputMu.Unlock()++ // Build usage map.+ c.usageMu.Lock()+ u := c.usage+ c.usageMu.Unlock()++ var usageMap map[string]TokenUsage+ if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 {+ model := opts.Model+ if model == "" {+ model = "unknown"+ }+ usageMap = map[string]TokenUsage{model: u}+ }++ resCh <- Result{+ Status: finalStatus,+ Output: finalOutput,+ Error: finalError,+ DurationMs: duration.Milliseconds(),+ SessionID: sessionID,+ Usage: usageMap,+ }+ }()++ return &Session{Messages: msgCh, Result: resCh}, nil+}++// ── hermesClient: ACP JSON-RPC 2.0 transport ──++type hermesPromptResult struct {+ stopReason string+ usage TokenUsage+}++type hermesClient struct {+ cfg Config+ stdin interface{ Write([]byte) (int, error) }+ mu sync.Mutex+ nextID int+ pending map[int]*pendingRPC+ sessionID string+ onMessage func(Message)+ onPromptDone func(hermesPromptResult)++ usageMu sync.Mutex+ usage TokenUsage+}++func (c *hermesClient) request(ctx context.Context, method string, params any) (json.RawMessage, error) {+ c.mu.Lock()+ id := c.nextID+ c.nextID+++ pr := &pendingRPC{ch: make(chan rpcResult, 1), method: method}+ c.pending[id] = pr+ c.mu.Unlock()++ msg := map[string]any{+ "jsonrpc": "2.0",+ "id": id,+ "method": method,+ "params": params,+ }+ data, err := json.Marshal(msg)+ if err != nil {+ c.mu.Lock()+ delete(c.pending, id)+ c.mu.Unlock()+ return nil, err+ }+ data = append(data, '\n')+ if _, err := c.stdin.Write(data); err != nil {+ c.mu.Lock()+ delete(c.pending, id)+ c.mu.Unlock()+ return nil, fmt.Errorf("write %s: %w", method, err)+ }++ select {+ case res := <-pr.ch:+ return res.result, res.err+ case <-ctx.Done():+ c.mu.Lock()+ delete(c.pending, id)+ c.mu.Unlock()+ return nil, ctx.Err()+ }+}++func (c *hermesClient) closeAllPending(err error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ for id, pr := range c.pending {+ pr.ch <- rpcResult{err: err}+ delete(c.pending, id)+ }+}++func (c *hermesClient) handleLine(line string) {+ var raw map[string]json.RawMessage+ if err := json.Unmarshal([]byte(line), &raw); err != nil {+ return+ }++ // Check if it's a response to our request (has id + result or error).+ if _, hasID := raw["id"]; hasID {+ if _, hasResult := raw["result"]; hasResult {+ c.handleResponse(raw)+ return+ }+ if _, hasError := raw["error"]; hasError {+ c.handleResponse(raw)+ return+ }+ }++ // Notification (no id, has method) — session updates from Hermes.+ if _, hasMethod := raw["method"]; hasMethod {+ c.handleNotification(raw)+ }+}++func (c *hermesClient) handleResponse(raw map[string]json.RawMessage) {+ var id int+ if err := json.Unmarshal(raw["id"], &id); err != nil {+ // Try float (JSON numbers are floats by default).+ var fid float64+ if err := json.Unmarshal(raw["id"], &fid); err != nil {+ return+ }+ id = int(fid)+ }++ c.mu.Lock()+ pr, ok := c.pending[id]+ if ok {+ delete(c.pending, id)+ }+ c.mu.Unlock()++ if !ok {+ return+ }++ if errData, hasErr := raw["error"]; hasErr {+ var rpcErr struct {+ Code int `json:"code"`+ Message string `json:"message"`+ }+ _ = json.Unmarshal(errData, &rpcErr)+ pr.ch <- rpcResult{err: fmt.Errorf("%s: %s (code=%d)", pr.method, rpcErr.Message, rpcErr.Code)}+ } else {+ // If this is a prompt response, extract usage and stop reason.+ if pr.method == "session/prompt" {+ c.extractPromptResult(raw["result"])+ }+ pr.ch <- rpcResult{result: raw["result"]}+ }+}++func (c *hermesClient) extractPromptResult(data json.RawMessage) {+ var resp struct {+ StopReason string `json:"stopReason"`+ Usage *struct {+ InputTokens int64 `json:"inputTokens"`+ OutputTokens int64 `json:"outputTokens"`+ TotalTokens int64 `json:"totalTokens"`+ ThoughtTokens int64 `json:"thoughtTokens"`+ CachedReadTokens int64 `json:"cachedReadTokens"`+ } `json:"usage"`+ }+ if err := json.Unmarshal(data, &resp); err != nil {+ return+ }++ pr := hermesPromptResult{+ stopReason: resp.StopReason,+ }+ if resp.Usage != nil {+ pr.usage = TokenUsage{+ InputTokens: resp.Usage.InputTokens,+ OutputTokens: resp.Usage.OutputTokens,+ CacheReadTokens: resp.Usage.CachedReadTokens,+ }+ }++ if c.onPromptDone != nil {+ c.onPromptDone(pr)+ }+}++func (c *hermesClient) handleNotification(raw map[string]json.RawMessage) {+ var method string+ _ = json.Unmarshal(raw["method"], &method)++ if method != "session/update" {+ return+ }++ var params struct {+ SessionID string `json:"sessionId"`+ Update json.RawMessage `json:"update"`+ }+ if p, ok := raw["params"]; ok {+ _ = json.Unmarshal(p, ¶ms)+ }+ if len(params.Update) == 0 {+ return+ }++ // Parse the update discriminator.+ var updateType struct {+ SessionUpdate string `json:"sessionUpdate"`+ }+ _ = json.Unmarshal(params.Update, &updateType)++ switch updateType.SessionUpdate {+ case "agent_message_chunk":+ c.handleAgentMessage(params.Update)+ case "agent_thought_chunk":+ c.handleAgentThought(params.Update)+ case "tool_call":+ c.handleToolCallStart(params.Update)+ case "tool_call_update":+ c.handleToolCallUpdate(params.Update)+ case "usage_update":+ c.handleUsageUpdate(params.Update)+ }+}++func (c *hermesClient) handleAgentMessage(data json.RawMessage) {+ var msg struct {+ Content struct {+ Type string `json:"type"`+ Text string `json:"text"`+ } `json:"content"`+ }+ if err := json.Unmarshal(data, &msg); err != nil || msg.Content.Text == "" {+ return+ }+ if c.onMessage != nil {+ c.onMessage(Message{Type: MessageText, Content: msg.Content.Text})+ }+}++func (c *hermesClient) handleAgentThought(data json.RawMessage) {+ var msg struct {+ Content struct {+ Type string `json:"type"`+ Text string `json:"text"`+ } `json:"content"`+ }+ if err := json.Unmarshal(data, &msg); err != nil || msg.Content.Text == "" {+ return+ }+ if c.onMessage != nil {+ c.onMessage(Message{Type: MessageThinking, Content: msg.Content.Text})+ }+}++func (c *hermesClient) handleToolCallStart(data json.RawMessage) {+ var msg struct {+ ToolCallID string `json:"toolCallId"`+ Title string `json:"title"`+ Kind string `json:"kind"`+ RawInput map[string]any `json:"rawInput"`+ }+ if err := json.Unmarshal(data, &msg); err != nil {+ return+ }++ toolName := hermesToolNameFromTitle(msg.Title, msg.Kind)+ if c.onMessage != nil {+ c.onMessage(Message{+ Type: MessageToolUse,+ Tool: toolName,+ CallID: msg.ToolCallID,+ Input: msg.RawInput,+ })+ }+}++func (c *hermesClient) handleToolCallUpdate(data json.RawMessage) {+ var msg struct {+ ToolCallID string `json:"toolCallId"`+ Status string `json:"status"`+ Kind string `json:"kind"`+ RawOutput string `json:"rawOutput"`+ }+ if err := json.Unmarshal(data, &msg); err != nil {+ return+ }++ // Only emit tool result when the call is completed.+ if msg.Status != "completed" && msg.Status != "failed" {+ return+ }++ if c.onMessage != nil {+ c.onMessage(Message{+ Type: MessageToolResult,+ CallID: msg.ToolCallID,+ Output: msg.RawOutput,+ })+ }+}++func (c *hermesClient) handleUsageUpdate(data json.RawMessage) {+ var msg struct {+ Usage struct {+ InputTokens int64 `json:"inputTokens"`+ OutputTokens int64 `json:"outputTokens"`+ TotalTokens int64 `json:"totalTokens"`+ CachedReadTokens int64 `json:"cachedReadTokens"`+ } `json:"usage"`+ }+ if err := json.Unmarshal(data, &msg); err != nil {+ return+ }++ c.usageMu.Lock()+ // Usage updates from ACP are cumulative snapshots, so take the latest.+ if msg.Usage.InputTokens > c.usage.InputTokens {+ c.usage.InputTokens = msg.Usage.InputTokens+ }+ if msg.Usage.OutputTokens > c.usage.OutputTokens {+ c.usage.OutputTokens = msg.Usage.OutputTokens+ }+ if msg.Usage.CachedReadTokens > c.usage.CacheReadTokens {+ c.usage.CacheReadTokens = msg.Usage.CachedReadTokens+ }+ c.usageMu.Unlock()+}++// ── Helpers ──++func extractHermesSessionID(result json.RawMessage) string {+ var r struct {+ SessionID string `json:"sessionId"`+ }+ if err := json.Unmarshal(result, &r); err != nil {+ return ""+ }+ return r.SessionID+}++// hermesToolNameFromTitle extracts a tool name from the ACP tool call title.+// Hermes ACP titles look like "terminal: ls -la", "read: /path/to/file", etc.+// Some titles have no colon (e.g. "execute code").+func hermesToolNameFromTitle(title string, kind string) string {+ // Check exact-match titles first (no colon).+ switch title {+ case "execute code":+ return "execute_code"+ }++ // Try to extract the tool name from before the first colon.+ if idx := strings.Index(title, ":"); idx > 0 {+ name := strings.TrimSpace(title[:idx])+ // Map common ACP title prefixes back to tool names.+ // Some titles include mode info like "patch (replace)", so check prefix.+ switch {+ case name == "terminal":+ return "terminal"+ case name == "read":+ return "read_file"+ case name == "write":+ return "write_file"+ case strings.HasPrefix(name, "patch"):+ return "patch"+ case name == "search":+ return "search_files"+ case name == "web search":+ return "web_search"+ case name == "extract":+ return "web_extract"+ case name == "delegate":+ return "delegate_task"+ case name == "analyze image":+ return "vision_analyze"+ }+ return name+ }++ // Fall back to kind.+ switch kind {+ case "read":+ return "read_file"+ case "edit":+ return "write_file"+ case "execute":+ return "terminal"+ case "search":+ return "search_files"+ case "fetch":+ return "web_search"+ case "think":+ return "thinking"+ default:+ return kind+ }+}diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.gonew file mode 100644index 0000000000..f61151f9c0--- /dev/null+++ b/server/pkg/agent/hermes_test.go@@ -0,0 +1,377 @@+package agent++import (+ "encoding/json"+ "testing"+)++func TestNewReturnsHermesBackend(t *testing.T) {+ t.Parallel()+ b, err := New("hermes", Config{ExecutablePath: "/nonexistent/hermes"})+ if err != nil {+ t.Fatalf("New(hermes) error: %v", err)+ }+ if _, ok := b.(*hermesBackend); !ok {+ t.Fatalf("expected *hermesBackend, got %T", b)+ }+}++// ── extractHermesSessionID ──++func TestExtractHermesSessionID(t *testing.T) {+ t.Parallel()+ raw := json.RawMessage(`{"sessionId":"20260410_141145_47260c"}`)+ got := extractHermesSessionID(raw)+ if got != "20260410_141145_47260c" {+ t.Errorf("got %q, want %q", got, "20260410_141145_47260c")+ }+}++func TestExtractHermesSessionIDEmpty(t *testing.T) {+ t.Parallel()+ raw := json.RawMessage(`{}`)+ got := extractHermesSessionID(raw)+ if got != "" {+ t.Errorf("got %q, want empty", got)+ }+}++func TestExtractHermesSessionIDInvalidJSON(t *testing.T) {+ t.Parallel()+ raw := json.RawMessage(`not json`)+ got := extractHermesSessionID(raw)+ if got != "" {+ t.Errorf("got %q, want empty", got)+ }+}++// ── hermesToolNameFromTitle ──++func TestHermesToolNameFromTitle(t *testing.T) {+ t.Parallel()+ tests := []struct {+ title string+ kind string+ want string+ }{+ {"terminal: ls -la", "execute", "terminal"},+ {"read: /tmp/foo.go", "read", "read_file"},+ {"write: /tmp/bar.go", "edit", "write_file"},+ {"patch (replace): /tmp/baz.go", "edit", "patch"},+ {"search: *.go", "search", "search_files"},+ {"web search: golang acp protocol", "fetch", "web_search"},+ {"extract: https://example.com", "fetch", "web_extract"},+ {"delegate: fix the bug", "execute", "delegate_task"},+ {"analyze image: what is this?", "read", "vision_analyze"},+ {"execute code", "execute", "execute_code"},+ // Fallback to kind when no colon in title.+ {"unknownTool", "read", "read_file"},+ {"unknownTool", "edit", "write_file"},+ {"unknownTool", "execute", "terminal"},+ {"unknownTool", "search", "search_files"},+ {"unknownTool", "fetch", "web_search"},+ {"unknownTool", "think", "thinking"},+ {"unknownTool", "other", "other"},+ // Tool with colon but not in known map.+ {"custom_tool: args", "other", "custom_tool"},+ }+ for _, tt := range tests {+ got := hermesToolNameFromTitle(tt.title, tt.kind)+ if got != tt.want {+ t.Errorf("hermesToolNameFromTitle(%q, %q) = %q, want %q", tt.title, tt.kind, got, tt.want)+ }+ }+}++// ── handleLine routing ──++func TestHermesClientHandleLineResponse(t *testing.T) {+ t.Parallel()++ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ }+ pr := &pendingRPC{ch: make(chan rpcResult, 1), method: "session/new"}+ c.pending[1] = pr++ c.handleLine(`{"jsonrpc":"2.0","id":1,"result":{"sessionId":"ses_abc"}}`)++ res := <-pr.ch+ if res.err != nil {+ t.Fatalf("unexpected error: %v", res.err)+ }+ sid := extractHermesSessionID(res.result)+ if sid != "ses_abc" {+ t.Errorf("sessionId: got %q, want %q", sid, "ses_abc")+ }+}++func TestHermesClientHandleLineError(t *testing.T) {+ t.Parallel()++ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ }+ pr := &pendingRPC{ch: make(chan rpcResult, 1), method: "initialize"}+ c.pending[0] = pr++ c.handleLine(`{"jsonrpc":"2.0","id":0,"error":{"code":-32600,"message":"bad request"}}`)++ res := <-pr.ch+ if res.err == nil {+ t.Fatal("expected error")+ }+ if got := res.err.Error(); got != "initialize: bad request (code=-32600)" {+ t.Errorf("error: got %q", got)+ }+}++// ── session/update notification handling ──++func TestHermesClientHandleAgentMessage(t *testing.T) {+ t.Parallel()++ var got Message+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onMessage: func(msg Message) {+ got = msg+ },+ }++ line := `{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello world"}}}}`+ c.handleLine(line)++ if got.Type != MessageText {+ t.Errorf("type: got %v, want MessageText", got.Type)+ }+ if got.Content != "Hello world" {+ t.Errorf("content: got %q, want %q", got.Content, "Hello world")+ }+}++func TestHermesClientHandleAgentThought(t *testing.T) {+ t.Parallel()++ var got Message+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onMessage: func(msg Message) {+ got = msg+ },+ }++ line := `{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Let me think..."}}}}`+ c.handleLine(line)++ if got.Type != MessageThinking {+ t.Errorf("type: got %v, want MessageThinking", got.Type)+ }+ if got.Content != "Let me think..." {+ t.Errorf("content: got %q, want %q", got.Content, "Let me think...")+ }+}++func TestHermesClientHandleToolCallStart(t *testing.T) {+ t.Parallel()++ var got Message+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onMessage: func(msg Message) {+ got = msg+ },+ }++ line := `{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"tool_call","toolCallId":"tc-abc123","title":"terminal: ls -la","kind":"execute","status":"pending","rawInput":{"command":"ls -la"}}}}`+ c.handleLine(line)++ if got.Type != MessageToolUse {+ t.Errorf("type: got %v, want MessageToolUse", got.Type)+ }+ if got.Tool != "terminal" {+ t.Errorf("tool: got %q, want %q", got.Tool, "terminal")+ }+ if got.CallID != "tc-abc123" {+ t.Errorf("callID: got %q, want %q", got.CallID, "tc-abc123")+ }+ if cmd, ok := got.Input["command"].(string); !ok || cmd != "ls -la" {+ t.Errorf("input.command: got %v", got.Input["command"])+ }+}++func TestHermesClientHandleToolCallComplete(t *testing.T) {+ t.Parallel()++ var got Message+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onMessage: func(msg Message) {+ got = msg+ },+ }++ line := `{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-abc123","status":"completed","kind":"execute","rawOutput":"file1.go\nfile2.go\n"}}}`+ c.handleLine(line)++ if got.Type != MessageToolResult {+ t.Errorf("type: got %v, want MessageToolResult", got.Type)+ }+ if got.CallID != "tc-abc123" {+ t.Errorf("callID: got %q, want %q", got.CallID, "tc-abc123")+ }+ if got.Output != "file1.go\nfile2.go\n" {+ t.Errorf("output: got %q", got.Output)+ }+}++func TestHermesClientHandleToolCallInProgressIgnored(t *testing.T) {+ t.Parallel()++ called := false+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onMessage: func(msg Message) {+ called = true+ },+ }++ line := `{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-abc123","status":"in_progress"}}}`+ c.handleLine(line)++ if called {+ t.Error("expected in_progress tool_call_update to be ignored")+ }+}++func TestHermesClientHandleUsageUpdate(t *testing.T) {+ t.Parallel()++ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ }++ line := `{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","usage":{"inputTokens":500,"outputTokens":200,"cachedReadTokens":100}}}}`+ c.handleLine(line)++ c.usageMu.Lock()+ defer c.usageMu.Unlock()++ if c.usage.InputTokens != 500 {+ t.Errorf("inputTokens: got %d, want 500", c.usage.InputTokens)+ }+ if c.usage.OutputTokens != 200 {+ t.Errorf("outputTokens: got %d, want 200", c.usage.OutputTokens)+ }+ if c.usage.CacheReadTokens != 100 {+ t.Errorf("cacheReadTokens: got %d, want 100", c.usage.CacheReadTokens)+ }+}++func TestHermesClientHandleUsageUpdateCumulative(t *testing.T) {+ t.Parallel()++ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ }++ // First usage update.+ c.handleLine(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","usage":{"inputTokens":100,"outputTokens":50}}}}`)++ // Second usage update with higher values (should take the max).+ c.handleLine(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","usage":{"inputTokens":300,"outputTokens":120}}}}`)++ c.usageMu.Lock()+ defer c.usageMu.Unlock()++ if c.usage.InputTokens != 300 {+ t.Errorf("inputTokens: got %d, want 300", c.usage.InputTokens)+ }+ if c.usage.OutputTokens != 120 {+ t.Errorf("outputTokens: got %d, want 120", c.usage.OutputTokens)+ }+}++// ── extractPromptResult ──++func TestHermesClientExtractPromptResult(t *testing.T) {+ t.Parallel()++ var got hermesPromptResult+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onPromptDone: func(result hermesPromptResult) {+ got = result+ },+ }++ data := json.RawMessage(`{"stopReason":"end_turn","usage":{"inputTokens":1000,"outputTokens":200,"cachedReadTokens":50}}`)+ c.extractPromptResult(data)++ if got.stopReason != "end_turn" {+ t.Errorf("stopReason: got %q, want %q", got.stopReason, "end_turn")+ }+ if got.usage.InputTokens != 1000 {+ t.Errorf("inputTokens: got %d, want 1000", got.usage.InputTokens)+ }+ if got.usage.OutputTokens != 200 {+ t.Errorf("outputTokens: got %d, want 200", got.usage.OutputTokens)+ }+ if got.usage.CacheReadTokens != 50 {+ t.Errorf("cacheReadTokens: got %d, want 50", got.usage.CacheReadTokens)+ }+}++func TestHermesClientExtractPromptResultNoUsage(t *testing.T) {+ t.Parallel()++ var got hermesPromptResult+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onPromptDone: func(result hermesPromptResult) {+ got = result+ },+ }++ data := json.RawMessage(`{"stopReason":"cancelled"}`)+ c.extractPromptResult(data)++ if got.stopReason != "cancelled" {+ t.Errorf("stopReason: got %q, want %q", got.stopReason, "cancelled")+ }+ if got.usage.InputTokens != 0 {+ t.Errorf("inputTokens: got %d, want 0", got.usage.InputTokens)+ }+}++func TestHermesClientIgnoresUnknownNotification(t *testing.T) {+ t.Parallel()++ called := false+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ onMessage: func(msg Message) {+ called = true+ },+ }++ // Unknown method should be silently ignored.+ c.handleLine(`{"jsonrpc":"2.0","method":"unknown/event","params":{}}`)++ if called {+ t.Error("expected unknown notification to be ignored")+ }+}++func TestHermesClientIgnoresInvalidJSON(t *testing.T) {+ t.Parallel()++ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ }++ // Should not panic.+ c.handleLine("not json at all")+ c.handleLine("")+ c.handleLine("{}")+}