Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6464 fix(agent): support ACP terminals for Kimi runtime (#7323)
iiwish668a4e06c327
diff --git a/server/pkg/agent/acp_terminal.go b/server/pkg/agent/acp_terminal.gonew file mode 100644index 0000000000..dc93ee72a8--- /dev/null+++ b/server/pkg/agent/acp_terminal.go@@ -0,0 +1,303 @@+package agent++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "os/exec"+ "runtime"+ "strings"+ "sync"+ "syscall"+ "time"+ "unicode/utf8"+)++const (+ defaultACPOutputByteLimit = 50_000+ acpTerminalProcessGroupCleanupTimeout = 2 * time.Second+)++// acpTerminal is the daemon-side implementation of ACP's terminal/* methods.+// ACP agents use these calls for shell tools when the client advertises the+// terminal capability. Output is retained as a bounded tail, matching ACP's+// truncation contract without allowing a command to grow memory unboundedly.+type acpTerminal struct {+ cmd *exec.Cmd+ mu sync.Mutex+ output []byte+ limit int+ truncated bool+ done chan struct{}+ exitStatus *acpTerminalExitStatus+}++type acpTerminalExitStatus struct {+ exitCode *uint32+ signal *string+}++type acpTerminalOutputWriter struct {+ terminal *acpTerminal+}++func (w acpTerminalOutputWriter) Write(p []byte) (int, error) {+ w.terminal.mu.Lock()+ defer w.terminal.mu.Unlock()++ w.terminal.output = append(w.terminal.output, p...)+ if w.terminal.limit > 0 && len(w.terminal.output) > w.terminal.limit {+ start := len(w.terminal.output) - w.terminal.limit+ // ACP output is a string, so truncation must never retain the tail of+ // a rune whose leading byte was discarded.+ for start < len(w.terminal.output) && !utf8.RuneStart(w.terminal.output[start]) {+ start+++ }+ w.terminal.output = append([]byte(nil), w.terminal.output[start:]...)+ w.terminal.truncated = true+ }+ return len(p), nil+}++func (t *acpTerminal) snapshot() (output string, truncated bool, exitStatus *acpTerminalExitStatus) {+ t.mu.Lock()+ defer t.mu.Unlock()++ raw := append([]byte(nil), t.output...)+ // A pipe read may split a multibyte rune across Write calls. Do not expose+ // that incomplete suffix; a later snapshot will include it once complete.+ if len(raw) > 0 {+ lastRune := len(raw) - 1+ for lastRune > 0 && !utf8.RuneStart(raw[lastRune]) {+ lastRune--+ }+ if !utf8.FullRune(raw[lastRune:]) {+ raw = raw[:lastRune]+ }+ }+ valid := bytes.ToValidUTF8(raw, []byte("\uFFFD"))+ if t.limit > 0 && len(valid) > t.limit {+ start := len(valid) - t.limit+ for start < len(valid) && !utf8.RuneStart(valid[start]) {+ start+++ }+ valid = valid[start:]+ }+ if t.exitStatus != nil {+ status := *t.exitStatus+ exitStatus = &status+ }+ return string(valid), t.truncated, exitStatus+}++func (t *acpTerminal) wait() {+ <-t.done+}++func (t *acpTerminal) kill() error {+ t.mu.Lock()+ cmd := t.cmd+ t.mu.Unlock()+ if cmd == nil || cmd.Process == nil {+ return nil+ }+ signalProcessGroup(cmd, syscall.SIGKILL)+ // Cmd.Wait only describes the direct process. On Unix, descendants can+ // remain in its process group after that process exits, especially when a+ // background child redirects inherited output. Confirm the entire group is+ // gone before terminal/kill or terminal/release reports success.+ if runtime.GOOS != "windows" && !waitProcessGroupGone(cmd, acpTerminalProcessGroupCleanupTimeout) {+ return fmt.Errorf("process group %d still active after %s", cmd.Process.Pid, acpTerminalProcessGroupCleanupTimeout)+ }+ return nil+}++func (c *hermesClient) acpTerminalCreate(params json.RawMessage) (map[string]any, error) {+ var p struct {+ Command string `json:"command"`+ Args []string `json:"args"`+ Env []struct {+ Name string `json:"name"`+ Value string `json:"value"`+ } `json:"env"`+ Cwd string `json:"cwd"`+ OutputByteLimit int `json:"outputByteLimit"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("terminal/create params: %w", err)+ }+ if strings.TrimSpace(p.Command) == "" {+ return nil, fmt.Errorf("terminal/create requires command")+ }++ cwd := p.Cwd+ if cwd == "" {+ cwd = c.terminalCwd+ }+ if cwd == "" {+ cwd = "."+ }++ env := append([]string(nil), c.terminalEnv...)+ for _, item := range p.Env {+ if item.Name == "" {+ continue+ }+ env = append(env, item.Name+"="+item.Value)+ }++ var cmd *exec.Cmd+ if len(p.Args) > 0 {+ cmd = NewCommand(p.Command, nil).exec(c.terminalContext(), p.Args...)+ } else if runtime.GOOS == "windows" {+ cmd = NewCommand("cmd.exe", nil).exec(c.terminalContext(), "/d", "/s", "/c", p.Command)+ } else {+ cmd = NewCommand("/bin/sh", nil).exec(c.terminalContext(), "-c", p.Command)+ }+ hideAgentWindow(cmd)+ configureProcessGroup(cmd)+ cmd.Cancel = func() error {+ signalProcessGroup(cmd, syscall.SIGKILL)+ return nil+ }+ cmd.Dir = cwd+ cmd.Env = env++ limit := p.OutputByteLimit+ if limit <= 0 {+ limit = defaultACPOutputByteLimit+ }+ t := &acpTerminal{cmd: cmd, limit: limit, done: make(chan struct{})}+ writer := acpTerminalOutputWriter{terminal: t}+ cmd.Stdout = writer+ cmd.Stderr = writer+ if err := startOwnedProcessTree(cmd, c.cfg.Logger); err != nil {+ return nil, fmt.Errorf("terminal/create start: %w", err)+ }++ id := c.nextACPTerminalID()+ c.terminalMu.Lock()+ if c.terminals == nil {+ c.terminals = make(map[string]*acpTerminal)+ }+ c.terminals[id] = t+ c.terminalMu.Unlock()++ go func() {+ defer releaseProcessGroup(cmd)+ err := cmd.Wait()+ status := &acpTerminalExitStatus{}+ if err == nil {+ code := uint32(0)+ status.exitCode = &code+ } else if exitErr, ok := err.(*exec.ExitError); ok {+ if code := exitErr.ExitCode(); code >= 0 {+ exitCode := uint32(code)+ status.exitCode = &exitCode+ } else {+ status.signal = acpProcessExitSignal(exitErr.ProcessState)+ }+ }+ t.mu.Lock()+ t.exitStatus = status+ t.mu.Unlock()+ close(t.done)+ }()++ return map[string]any{"terminalId": id}, nil+}++func (c *hermesClient) terminalContext() context.Context {+ // The ACP transport is normally attached to a live task context. A nil+ // context is not valid for CommandContext, so keep this defensive fallback+ // for unit tests that construct hermesClient directly.+ if c.terminalCtx != nil {+ return c.terminalCtx+ }+ return context.Background()+}++func (c *hermesClient) nextACPTerminalID() string {+ c.terminalMu.Lock()+ defer c.terminalMu.Unlock()+ c.nextTerminalID+++ return fmt.Sprintf("multica-terminal-%d", c.nextTerminalID)+}++func (c *hermesClient) acpTerminalFor(id string) (*acpTerminal, bool) {+ c.terminalMu.Lock()+ defer c.terminalMu.Unlock()+ t, ok := c.terminals[id]+ return t, ok+}++func (c *hermesClient) acpTerminalRelease(id string) error {+ c.terminalMu.Lock()+ t, ok := c.terminals[id]+ c.terminalMu.Unlock()+ if !ok {+ return nil+ }+ if err := t.kill(); err != nil {+ return fmt.Errorf("release terminal %q: %w", id, err)+ }++ // Delete only after cleanup is confirmed so a failed release can be retried.+ c.terminalMu.Lock()+ if c.terminals[id] == t {+ delete(c.terminals, id)+ }+ c.terminalMu.Unlock()+ return nil+}++func (c *hermesClient) acpTerminalResponse(method string, params json.RawMessage) (map[string]any, error) {+ var p struct {+ TerminalID string `json:"terminalId"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("%s params: %w", method, err)+ }+ t, ok := c.acpTerminalFor(p.TerminalID)+ if !ok {+ return nil, fmt.Errorf("unknown terminal %q", p.TerminalID)+ }++ switch method {+ case "terminal/output":+ output, truncated, exitStatus := t.snapshot()+ result := map[string]any{"output": output, "truncated": truncated}+ if exitStatus != nil {+ result["exitStatus"] = acpTerminalExitStatusResult(exitStatus)+ }+ return result, nil+ case "terminal/wait_for_exit":+ t.wait()+ _, _, exitStatus := t.snapshot()+ if exitStatus == nil {+ return nil, fmt.Errorf("terminal %q exited without status", p.TerminalID)+ }+ return acpTerminalExitStatusResult(exitStatus), nil+ case "terminal/kill":+ if err := t.kill(); err != nil {+ return nil, fmt.Errorf("kill terminal %q: %w", p.TerminalID, err)+ }+ return map[string]any{}, nil+ case "terminal/release":+ return map[string]any{}, c.acpTerminalRelease(p.TerminalID)+ default:+ return nil, fmt.Errorf("unsupported terminal method %q", method)+ }+}++func acpTerminalExitStatusResult(status *acpTerminalExitStatus) map[string]any {+ result := map[string]any{"exitCode": nil, "signal": nil}+ if status.exitCode != nil {+ result["exitCode"] = int(*status.exitCode)+ }+ if status.signal != nil {+ result["signal"] = *status.signal+ }+ return result+}diff --git a/server/pkg/agent/acp_terminal_other_test.go b/server/pkg/agent/acp_terminal_other_test.gonew file mode 100644index 0000000000..7610364a38--- /dev/null+++ b/server/pkg/agent/acp_terminal_other_test.go@@ -0,0 +1,155 @@+//go:build !windows++package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "syscall"+ "testing"+ "time"+)++func TestACPManagedTerminalKillTerminatesProcessTree(t *testing.T) {+ t.Parallel()++ pidFile := filepath.Join(t.TempDir(), "child.pid")+ c := &hermesClient{+ terminalCtx: context.Background(),+ terminalCwd: t.TempDir(),+ terminalEnv: os.Environ(),+ terminals: make(map[string]*acpTerminal),+ }+ params, err := json.Marshal(map[string]any{+ "sessionId": "s",+ "command": "/bin/sh",+ "args": []string{"-c", fmt.Sprintf("sleep 30 & child=$!; echo $child > %q; wait $child", pidFile)},+ })+ if err != nil {+ t.Fatal(err)+ }+ created, err := c.acpTerminalCreate(params)+ if err != nil {+ t.Fatal(err)+ }+ id := created["terminalId"].(string)+ defer c.acpTerminalRelease(id)++ childPID := waitForACPChildPID(t, pidFile, 2*time.Second)+ defer syscall.Kill(childPID, syscall.SIGKILL)+ request := json.RawMessage(`{"sessionId":"s","terminalId":"` + id + `"}`)+ if _, err := c.acpTerminalResponse("terminal/kill", request); err != nil {+ t.Fatal(err)+ }+ status, err := c.acpTerminalResponse("terminal/wait_for_exit", request)+ if err != nil {+ t.Fatal(err)+ }+ if status["exitCode"] != nil {+ t.Fatalf("exitCode = %#v, want null for signal exit", status["exitCode"])+ }+ if signal, ok := status["signal"].(string); !ok || signal == "" {+ t.Fatalf("signal = %#v, want signal name", status["signal"])+ }++ deadline := time.Now().Add(2 * time.Second)+ for processExists(childPID) && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ if processExists(childPID) {+ t.Fatalf("terminal child process %d survived terminal/kill", childPID)+ }+}++func TestACPManagedTerminalReleaseTerminatesProcessTreeAfterParentExit(t *testing.T) {+ t.Parallel()++ pidFile := filepath.Join(t.TempDir(), "child.pid")+ c := &hermesClient{+ terminalCtx: context.Background(),+ terminalCwd: t.TempDir(),+ terminalEnv: os.Environ(),+ terminals: make(map[string]*acpTerminal),+ }+ params, err := json.Marshal(map[string]any{+ "sessionId": "s",+ "command": "/bin/sh",+ "args": []string{"-c", fmt.Sprintf(+ "sleep 30 >/dev/null 2>&1 & child=$!; echo $child > %q",+ pidFile,+ )},+ })+ if err != nil {+ t.Fatal(err)+ }+ created, err := c.acpTerminalCreate(params)+ if err != nil {+ t.Fatal(err)+ }+ id := created["terminalId"].(string)+ terminal, ok := c.acpTerminalFor(id)+ if !ok {+ t.Fatalf("terminal %q was not registered", id)+ }+ processGroupID := terminal.cmd.Process.Pid+ childPID := waitForACPChildPID(t, pidFile, 2*time.Second)+ childNeedsCleanup := true+ defer func() {+ if childNeedsCleanup {+ _ = syscall.Kill(childPID, syscall.SIGKILL)+ }+ }()++ request := json.RawMessage(`{"sessionId":"s","terminalId":"` + id + `"}`)+ status, err := c.acpTerminalResponse("terminal/wait_for_exit", request)+ if err != nil {+ t.Fatal(err)+ }+ if got := status["exitCode"]; got != 0 {+ t.Fatalf("parent exitCode = %#v, want 0", got)+ }+ if !processExists(childPID) {+ t.Fatalf("background child process %d exited before terminal/release", childPID)+ }++ if _, err := c.acpTerminalResponse("terminal/release", request); err != nil {+ t.Fatal(err)+ }+ if processExists(childPID) {+ t.Fatalf("terminal child process %d still exists after terminal/release returned", childPID)+ }+ childNeedsCleanup = false+ if err := syscall.Kill(-processGroupID, 0); !errors.Is(err, syscall.ESRCH) {+ t.Fatalf("process group %d still exists after terminal/release: %v", processGroupID, err)+ }+ if _, ok := c.acpTerminalFor(id); ok {+ t.Fatalf("terminal %q remained registered after terminal/release", id)+ }+}++func waitForACPChildPID(t *testing.T, path string, timeout time.Duration) int {+ t.Helper()+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ raw, err := os.ReadFile(path)+ if err == nil {+ pid, parseErr := strconv.Atoi(strings.TrimSpace(string(raw)))+ if parseErr == nil && pid > 0 {+ return pid+ }+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Fatal("terminal child process did not start")+ return 0+}++func processExists(pid int) bool {+ return syscall.Kill(pid, 0) == nil+}diff --git a/server/pkg/agent/acp_terminal_status_other.go b/server/pkg/agent/acp_terminal_status_other.gonew file mode 100644index 0000000000..d86217622f--- /dev/null+++ b/server/pkg/agent/acp_terminal_status_other.go@@ -0,0 +1,20 @@+//go:build !windows++package agent++import (+ "os"+ "syscall"+)++func acpProcessExitSignal(state *os.ProcessState) *string {+ if state == nil {+ return nil+ }+ status, ok := state.Sys().(syscall.WaitStatus)+ if !ok || !status.Signaled() {+ return nil+ }+ signal := status.Signal().String()+ return &signal+}diff --git a/server/pkg/agent/acp_terminal_status_windows.go b/server/pkg/agent/acp_terminal_status_windows.gonew file mode 100644index 0000000000..a59646d843--- /dev/null+++ b/server/pkg/agent/acp_terminal_status_windows.go@@ -0,0 +1,9 @@+//go:build windows++package agent++import "os"++func acpProcessExitSignal(*os.ProcessState) *string {+ return nil+}diff --git a/server/pkg/agent/acp_terminal_test.go b/server/pkg/agent/acp_terminal_test.gonew file mode 100644index 0000000000..60671c5e92--- /dev/null+++ b/server/pkg/agent/acp_terminal_test.go@@ -0,0 +1,222 @@+package agent++import (+ "bytes"+ "context"+ "encoding/json"+ "os"+ "runtime"+ "strconv"+ "strings"+ "sync"+ "testing"+ "time"+ "unicode/utf8"+)++type acpTerminalResponseRecorder struct {+ mu sync.Mutex+ buffer bytes.Buffer+ changed chan struct{}+}++func (r *acpTerminalResponseRecorder) Write(p []byte) (int, error) {+ r.mu.Lock()+ n, err := r.buffer.Write(p)+ r.mu.Unlock()+ select {+ case r.changed <- struct{}{}:+ default:+ }+ return n, err+}++func (r *acpTerminalResponseRecorder) containsID(id int) bool {+ r.mu.Lock()+ defer r.mu.Unlock()+ return strings.Contains(r.buffer.String(), `"id":`+strconv.Itoa(id))+}++func TestACPManagedTerminalRunsAndReturnsOutput(t *testing.T) {+ t.Parallel()++ command := "printf 'hello from terminal'"+ if runtime.GOOS == "windows" {+ command = "echo hello from terminal"+ }+ c := &hermesClient{+ terminalCtx: cxtBackground(),+ terminalCwd: t.TempDir(),+ terminalEnv: os.Environ(),+ terminals: make(map[string]*acpTerminal),+ }++ created, err := c.acpTerminalCreate(json.RawMessage(`{"command":` + jsonString(command) + `}`))+ if err != nil {+ t.Fatalf("create: %v", err)+ }+ id, ok := created["terminalId"].(string)+ if !ok || id == "" {+ t.Fatalf("create result terminalId = %#v", created["terminalId"])+ }++ waited, err := c.acpTerminalResponse("terminal/wait_for_exit", json.RawMessage(`{"terminalId":`+jsonString(id)+`}`))+ if err != nil {+ t.Fatalf("wait: %v", err)+ }+ if got := waited["exitCode"]; got != float64(0) && got != 0 {+ t.Fatalf("exitCode = %#v, want 0", got)+ }++ output, err := c.acpTerminalResponse("terminal/output", json.RawMessage(`{"terminalId":`+jsonString(id)+`}`))+ if err != nil {+ t.Fatalf("output: %v", err)+ }+ if !strings.Contains(output["output"].(string), "hello from terminal") {+ t.Fatalf("output = %#v", output["output"])+ }+ if output["truncated"] != false {+ t.Fatalf("truncated = %#v, want false", output["truncated"])+ }++ if err := c.acpTerminalRelease(id); err != nil {+ t.Fatalf("release: %v", err)+ }+}++func TestACPManagedTerminalBoundsOutputToTail(t *testing.T) {+ t.Parallel()++ command := "printf '0123456789'"+ if runtime.GOOS == "windows" {+ command = "echo 0123456789"+ }+ c := &hermesClient{+ terminalCtx: cxtBackground(),+ terminalCwd: t.TempDir(),+ terminalEnv: os.Environ(),+ terminals: make(map[string]*acpTerminal),+ }+ created, err := c.acpTerminalCreate(json.RawMessage(`{"command":` + jsonString(command) + `,"outputByteLimit":4}`))+ if err != nil {+ t.Fatalf("create: %v", err)+ }+ id := created["terminalId"].(string)+ if _, err := c.acpTerminalResponse("terminal/wait_for_exit", json.RawMessage(`{"terminalId":`+jsonString(id)+`}`)); err != nil {+ t.Fatalf("wait: %v", err)+ }+ output, err := c.acpTerminalResponse("terminal/output", json.RawMessage(`{"terminalId":`+jsonString(id)+`}`))+ if err != nil {+ t.Fatalf("output: %v", err)+ }+ if output["truncated"] != true {+ t.Fatalf("truncated = %#v, want true", output["truncated"])+ }+ if len(output["output"].(string)) != 4 {+ t.Fatalf("output length = %d, want 4", len(output["output"].(string)))+ }+ _ = c.acpTerminalRelease(id)+}++func TestACPManagedTerminalTruncatesAtUTF8Boundary(t *testing.T) {+ t.Parallel()++ terminal := &acpTerminal{limit: 4}+ writer := acpTerminalOutputWriter{terminal: terminal}+ if _, err := writer.Write([]byte("界界")); err != nil {+ t.Fatal(err)+ }+ output, truncated, _ := terminal.snapshot()+ if !truncated {+ t.Fatal("truncated = false, want true")+ }+ if !utf8.ValidString(output) {+ t.Fatalf("output is invalid UTF-8: %x", []byte(output))+ }+ if output != "界" {+ t.Fatalf("output = %q, want one complete trailing rune", output)+ }+}++func TestACPManagedTerminalHidesIncompleteUTF8Suffix(t *testing.T) {+ t.Parallel()++ terminal := &acpTerminal{limit: 10}+ writer := acpTerminalOutputWriter{terminal: terminal}+ encoded := []byte("界")+ if _, err := writer.Write(encoded[:2]); err != nil {+ t.Fatal(err)+ }+ if output, _, _ := terminal.snapshot(); output != "" {+ t.Fatalf("partial-rune output = %q, want empty", output)+ }+ if _, err := writer.Write(encoded[2:]); err != nil {+ t.Fatal(err)+ }+ if output, _, _ := terminal.snapshot(); output != "界" {+ t.Fatalf("completed-rune output = %q, want 界", output)+ }+}++func TestACPManagedTerminalWaitKeepsReaderResponsive(t *testing.T) {+ t.Parallel()++ done := make(chan struct{})+ closed := false+ defer func() {+ if !closed {+ close(done)+ }+ }()+ zero := uint32(0)+ recorder := &acpTerminalResponseRecorder{changed: make(chan struct{}, 4)}+ c := &hermesClient{+ stdin: recorder,+ terminalEnabled: true,+ terminals: map[string]*acpTerminal{+ "term": {+ done: done,+ exitStatus: &acpTerminalExitStatus{exitCode: &zero},+ },+ },+ }++ dispatched := make(chan struct{})+ go func() {+ c.handleLine(`{"jsonrpc":"2.0","id":1,"method":"terminal/wait_for_exit","params":{"sessionId":"s","terminalId":"term"}}`)+ c.handleLine(`{"jsonrpc":"2.0","id":2,"method":"terminal/output","params":{"sessionId":"s","terminalId":"term"}}`)+ close(dispatched)+ }()++ waitForACPResponseID(t, recorder, 2, time.Second)+ close(done)+ closed = true+ waitForACPResponseID(t, recorder, 1, time.Second)+ select {+ case <-dispatched:+ case <-time.After(time.Second):+ t.Fatal("ACP reader did not finish dispatching terminal requests")+ }+}++func waitForACPResponseID(t *testing.T, recorder *acpTerminalResponseRecorder, id int, timeout time.Duration) {+ t.Helper()+ deadline := time.NewTimer(timeout)+ defer deadline.Stop()+ for !recorder.containsID(id) {+ select {+ case <-recorder.changed:+ case <-deadline.C:+ t.Fatalf("timeout waiting for ACP response id %d", id)+ }+ }+}++// These tiny helpers keep the test JSON readable without introducing a+// second JSON encoder abstraction into the production ACP transport.+func cxtBackground() context.Context { return context.Background() }++func jsonString(s string) string {+ b, _ := json.Marshal(s)+ return string(b)+}diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 1bb14918f4..3a5932baf2 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -925,6 +925,17 @@ type hermesClient struct {usageMu sync.Mutexusage acpUsageAccumulator++ // terminalEnabled is only set for ACP runtimes whose client-side terminal+ // calls are implemented below. Keeping it opt-in avoids advertising a+ // capability to Hermes-family runtimes that do not need it.+ terminalEnabled bool+ terminalCtx context.Context+ terminalCwd string+ terminalEnv []string+ terminalMu sync.Mutex+ terminals map[string]*acpTerminal+ nextTerminalID int}// pendingToolCall buffers state for a tool call while its arguments@@ -1031,11 +1042,11 @@ func (c *hermesClient) handleLine(line string) {}// handleAgentRequest replies to JSON-RPC requests the agent sends-// us (agent → client direction). The only one we care about today is-// `session/request_permission`: the daemon is headless and cannot-// actually prompt a user, so we answer it ourselves — granting when a-// safe option is offered, otherwise declining just this action or-// failing closed (see below).+// us (agent → client direction). Kimi's ACP terminal capability is+// implemented here alongside the permission request handling: the daemon is+// headless and cannot actually prompt a user, so we answer permission requests+// ourselves — granting when a safe option is offered, otherwise declining+// just this action or failing closed (see below).//// The reply MUST select one of the optionIds the agent actually// offered — the ACP permission contract is "pick from these options",@@ -1057,9 +1068,86 @@ func (c *hermesClient) handleAgentRequest(raw map[string]json.RawMessage) {if !ok {return}+ if method == "terminal/wait_for_exit" && c.terminalEnabled {+ // wait_for_exit is intentionally long-lived. The ACP reader must remain+ // available for the output polling and terminal/kill requests Kimi sends+ // while this request is pending.+ id := append(json.RawMessage(nil), rawID...)+ params := append(json.RawMessage(nil), raw["params"]...)+ go func() {+ result, err := c.acpTerminalResponse(method, params)+ if err != nil {+ c.writeAgentRequestResponse(method, map[string]any{+ "jsonrpc": "2.0",+ "id": id,+ "error": map[string]any{+ "code": -32602,+ "message": err.Error(),+ },+ })+ return+ }+ c.writeAgentRequestResponse(method, map[string]any{+ "jsonrpc": "2.0",+ "id": id,+ "result": result,+ })+ }()+ return+ }var resp map[string]anyswitch method {+ case "terminal/create":+ if !c.terminalEnabled {+ resp = map[string]any{+ "jsonrpc": "2.0",+ "id": json.RawMessage(rawID),+ "error": map[string]any{+ "code": -32601,+ "message": "terminal capability is not enabled",+ },+ }+ break+ }+ result, err := c.acpTerminalCreate(raw["params"])+ if err != nil {+ resp = map[string]any{+ "jsonrpc": "2.0",+ "id": json.RawMessage(rawID),+ "error": map[string]any{+ "code": -32602,+ "message": err.Error(),+ },+ }+ break+ }+ resp = map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(rawID), "result": result}+ case "terminal/output", "terminal/wait_for_exit", "terminal/kill", "terminal/release":+ if !c.terminalEnabled {+ resp = map[string]any{+ "jsonrpc": "2.0",+ "id": json.RawMessage(rawID),+ "error": map[string]any{+ "code": -32601,+ "message": "terminal capability is not enabled",+ },+ }+ break+ }+ result, err := c.acpTerminalResponse(method, raw["params"])+ if err != nil {+ resp = map[string]any{+ "jsonrpc": "2.0",+ "id": json.RawMessage(rawID),+ "error": map[string]any{+ "code": -32602,+ "message": err.Error(),+ },+ }+ break+ }+ resp = map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(rawID), "result": result}case "session/request_permission":selector := c.selectPermissionif selector == nil {@@ -1118,14 +1206,26 @@ func (c *hermesClient) handleAgentRequest(raw map[string]json.RawMessage) {c.cfg.Logger.Debug("unhandled agent→client request", "method", method)}+ c.writeAgentRequestResponse(method, resp)+}++func (c *hermesClient) writeAgentRequestResponse(method string, resp map[string]any) {data, err := json.Marshal(resp)if err != nil {- c.cfg.Logger.Warn("marshal agent-request response", "method", method, "error", err)+ logger := c.cfg.Logger+ if logger == nil {+ logger = slog.Default()+ }+ logger.Warn("marshal agent-request response", "method", method, "error", err)return}data = append(data, '\n')if err := c.writeLine(data); err != nil {- c.cfg.Logger.Warn("write agent-request response", "method", method, "error", err)+ logger := c.cfg.Logger+ if logger == nil {+ logger = slog.Default()+ }+ logger.Warn("write agent-request response", "method", method, "error", err)}}@@ -1869,11 +1969,9 @@ func acpRawText(raw json.RawMessage) string {return string(raw)}-// Terminal blocks ({type:"terminal", terminalId}) reference a remote-// terminal the client would normally subscribe to via terminal/output;-// we don't advertise terminal capability so we never receive those in-// practice, but if one slips through we skip it (nothing useful to-// surface from a bare ID).+// Terminal blocks ({type:"terminal", terminalId}) reference a terminal whose+// output is served through terminal/output. The textual extractor has no+// payload to duplicate here; the ACP transport retains the terminal output.func extractACPToolCallText(blocks []json.RawMessage) string {var b strings.BuilderappendPiece := func(piece string) {diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.goindex 331ebb90dd..b51a1e5b47 100644--- a/server/pkg/agent/kimi.go+++ b/server/pkg/agent/kimi.go@@ -135,10 +135,15 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// Reuse the hermesClient ACP transport — Kimi speaks the same protocol.c := &hermesClient{- cfg: b.cfg,- stdin: stdin,- pending: make(map[int]*pendingRPC),- pendingTools: make(map[string]*pendingToolCall),+ cfg: b.cfg,+ stdin: stdin,+ pending: make(map[int]*pendingRPC),+ pendingTools: make(map[string]*pendingToolCall),+ terminalEnabled: true,+ terminalCtx: runCtx,+ terminalCwd: opts.Cwd,+ terminalEnv: buildEnv(b.cfg.Env),+ terminals: make(map[string]*acpTerminal),acceptNotification: func(string) bool {return streamingCurrentTurn.Load()},@@ -218,7 +223,9 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio"name": "multica-agent-sdk","version": "0.2.0",},- "clientCapabilities": map[string]any{},+ "clientCapabilities": map[string]any{+ "terminal": true,+ },})if err != nil {finalStatus = "failed"diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.goindex a4ba7c0f57..cac8a9f03f 100644--- a/server/pkg/agent/kimi_test.go+++ b/server/pkg/agent/kimi_test.go@@ -673,6 +673,13 @@ func TestKimiFreshSessionIncludesMcpServers(t *testing.T) {t.Fatal("timeout waiting for result")}+ initFrame := findRecordedFrame(t, recordPath, "initialize")+ initParams := initFrame["params"].(map[string]any)+ capabilities := initParams["clientCapabilities"].(map[string]any)+ if capabilities["terminal"] != true {+ t.Fatalf("initialize.clientCapabilities.terminal = %#v, want true", capabilities["terminal"])+ }+frame := findRecordedFrame(t, recordPath, "session/new")params := frame["params"].(map[string]any)servers, ok := params["mcpServers"].([]any)