Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): MUL-8307 drive OpenCode over ACP so long tools and subagents are not force-stopped (#9619)
Multica Eve7d02596fc362
diff --git a/server/internal/daemon/opencode_clock_unix_test.go b/server/internal/daemon/opencode_clock_unix_test.goindex c4dace457f..ae0142d9ed 100644--- a/server/internal/daemon/opencode_clock_unix_test.go+++ b/server/internal/daemon/opencode_clock_unix_test.go@@ -28,6 +28,8 @@ func TestRunTaskOpenCodeClockSkew(t *testing.T) {}t.Run(name, func(t *testing.T) {redirectTestHome(t, t.TempDir())+ // The fake CLI speaks `opencode run`; pin that transport.+ t.Setenv("MULTICA_OPENCODE_TRANSPORT", "run")dir := t.TempDir()bin := filepath.Join(dir, "opencode")argsPath, promptPath := filepath.Join(dir, "args"), filepath.Join(dir, "prompt")diff --git a/server/internal/daemon/opencode_v2_mcp_wiring_test.go b/server/internal/daemon/opencode_v2_mcp_wiring_test.goindex 04f3260697..17a0f61687 100644--- a/server/internal/daemon/opencode_v2_mcp_wiring_test.go+++ b/server/internal/daemon/opencode_v2_mcp_wiring_test.go@@ -55,6 +55,7 @@ func TestOpenCodeV2RefusesSynthesizedMCPWithoutAgentConfig(t *testing.T) {ExecutablePath: fakeCLI,CLIVersion: "opencode v2.0.10",BuiltinRuntime: true,+ Env: map[string]string{"MULTICA_OPENCODE_TRANSPORT": "run"},Logger: slog.Default(),})if err != nil {diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 814975b043..6643319fcd 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -1204,6 +1204,31 @@ type hermesClient struct {// so for it the start frame is genuinely incomplete.toolStartCarriesFinalInput bool+ // toolInputArrivesInProgress marks a dialect (OpenCode) whose tool_call+ // start frame is sent while the model is still producing the call, with a+ // placeholder rawInput (`{}` or just the shell cwd), and whose first+ // in_progress tool_call_update carries the final input (possibly empty)+ // at the moment the tool starts executing. MessageToolUse is emitted at that update: early+ // enough for the daemon to charge a long tool to AgentToolWatchdog, and+ // late enough to record the actual invocation. Unset keeps the existing+ // start-frame handling for every other backend.+ toolInputArrivesInProgress bool+ // toolName optionally replaces the hermes title-based tool naming for a+ // dialect that reports its own tool ids. name is the update's `name`+ // field (absent on some dialects), title its `title`. Nil keeps+ // hermesToolNameFromTitle.+ toolName func(name, title, kind string) string+ // toolOutputFromContent prefers a completed tool call's display content+ // over its rawOutput. OpenCode's rawOutput is a metadata envelope (on 2.x+ // it carries no output text at all); the content blocks hold what the tool+ // printed.+ toolOutputFromContent bool+ // acceptUpdate can drop an individual session/update after the+ // lifecycle gate above, with the update payload in hand. OpenCode 2.x+ // uses it to keep a subagent's own text out of the parent's transcript.+ // Nil accepts every update.+ acceptUpdate func(updateType string, update json.RawMessage) bool+// pendingTools buffers the args for tool calls whose input streams in// across multiple ACP tool_call_update messages (kimi does this —// tokens from the LLM arrive one at a time, and each update carries@@ -1872,6 +1897,9 @@ func (c *hermesClient) handleNotification(raw map[string]json.RawMessage) {if c.acceptNotification != nil && !c.acceptNotification(updateType) {return}+ if c.acceptUpdate != nil && !c.acceptUpdate(updateType, updateData) {+ return+ }if c.onActivity != nil {c.onActivity()}@@ -1986,6 +2014,9 @@ func (c *hermesClient) handleToolCallStart(data json.RawMessage) {if toolName == "" {toolName = msg.Name}+ if c.toolName != nil {+ toolName = c.toolName(msg.Name, msg.Title, msg.Kind)+ }rawInput := msg.RawInputif rawInput == nil {rawInput = msg.Input@@ -1994,6 +2025,14 @@ func (c *hermesClient) handleToolCallStart(data json.RawMessage) {rawInput = msg.Parameters}+ // The start frame's rawInput is a placeholder on this dialect; buffer+ // the call and emit it from the first in_progress update instead (see+ // toolInputArrivesInProgress).+ if c.toolInputArrivesInProgress {+ c.trackTool(msg.ToolCallID, &pendingToolCall{toolName: toolName})+ return+ }+// Hermes pre-populates rawInput on the initial tool_call — emit// MessageToolUse immediately so the UI can show the tool invocation// live. Record the emission so handleToolCallUpdate doesn't re-emit@@ -2118,6 +2157,23 @@ func (c *hermesClient) handleToolCallUpdate(data json.RawMessage) {// tool call, each carrying the cumulative args JSON so far.if msg.Status != "completed" && msg.Status != "failed" {if pending := c.getPendingTool(msg.ToolCallID); pending != nil && !pending.emitted {+ if c.toolInputArrivesInProgress {+ // in_progress means the tool is executing, so its input is+ // final even when empty (a tool that takes no arguments).+ if msg.Status == "in_progress" {+ pending.input = rawInput+ pending.emitted = true+ if c.onMessage != nil {+ c.onMessage(Message{+ Type: MessageToolUse,+ Tool: pending.toolName,+ CallID: msg.ToolCallID,+ Input: rawInput,+ })+ }+ }+ return+ }if text := extractACPToolCallText(msg.Content); text != "" {// kimi streams the full cumulative args on every frame;// overwrite rather than concatenate.@@ -2131,7 +2187,13 @@ func (c *hermesClient) handleToolCallUpdate(data json.RawMessage) {pending := c.takePendingTool(msg.ToolCallID)c.emitDeferredToolUse(pending, msg.ToolCallID, title, msg.Kind, rawInput)- output := acpRawText(msg.RawOutput)+ var output string+ if c.toolOutputFromContent {+ output = extractACPToolCallText(msg.Content)+ }+ if output == "" {+ output = acpRawText(msg.RawOutput)+ }if output == "" {output = acpRawText(msg.Output)}@@ -2225,6 +2287,9 @@ func (c *hermesClient) emitDeferredToolUse(// No record of the start frame — fall back to the update's own// title/kind/rawInput so the UI at least sees the tool name.toolName = hermesToolNameFromTitle(updateTitle, updateKind)+ if c.toolName != nil {+ toolName = c.toolName("", updateTitle, updateKind)+ }input = updateRawInput}diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.goindex f647f19040..cf01bf94a0 100644--- a/server/pkg/agent/opencode.go+++ b/server/pkg/agent/opencode.go@@ -40,8 +40,10 @@ var opencodeBlockedArgs = map[string]blockedArgMode{"--dangerously-skip-permissions": blockedStandalone, // daemon manages non-interactive permission prompts}-// opencodeBackend implements Backend by spawning `opencode run --format json`-// and reading streaming JSON events from stdout — the same pattern as Claude.+// opencodeBackend implements Backend for OpenCode. Built-in 1.15+ and 2.x+// runtimes are driven over ACP (`opencode acp`, opencode_acp.go); everything+// else spawns `opencode run --format json` and reads streaming JSON events from+// stdout — the same pattern as Claude.type opencodeBackend struct {cfg Config// session is per-run state, set by Execute on the copy it scans with, so@@ -143,6 +145,14 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOif err != nil {return nil, err}+ // ACP streams tool starts, which the daemon needs to tell a long tool from+ // a hang; see opencode_acp.go. Everything below is the run transport, kept+ // as the fallback.+ if useACP, reason := opencodeUsesACP(b.cfg, opts); useACP {+ return b.executeACP(ctx, execPath, prompt, opts)+ } else {+ b.cfg.Logger.Info("opencode: using the run transport", "reason", reason)+ }timeout := opts.TimeoutrunCtx, cancel := runContext(ctx, timeout)@@ -673,11 +683,13 @@ func (b *opencodeBackend) handleToolUseEvent(event opencodeEvent, ch chan<- Mess_ = json.Unmarshal(event.Part.State.Input, &input)}+ callID := event.Part.toolCallID()+// Emit the tool-use message.trySend(ch, Message{Type: MessageToolUse,Tool: event.Part.Tool,- CallID: event.Part.CallID,+ CallID: callID,Input: input,})@@ -693,7 +705,7 @@ func (b *opencodeBackend) handleToolUseEvent(event opencodeEvent, ch chan<- MesstrySend(ch, Message{Type: MessageToolResult,Tool: event.Part.Tool,- CallID: event.Part.CallID,+ CallID: callID,Output: outputStr,})}@@ -792,7 +804,8 @@ func extractToolOutput(output any) string {//// "step_start" — agent step begins// "text" — text output from agent (part.text)-// "tool_use" — tool invocation with call and result (part.tool, part.callID, part.state)+// "tool_use" — tool invocation with call and result (part.tool, part.state, and+// the call id in part.callID on 1.x or part.id on 2.x)// "error" — error from opencode (error.name, error.data.message)// "step_finish" — agent step completes (includes token usage)type opencodeEvent struct {@@ -834,6 +847,21 @@ type opencodeEventPart struct {Reason string `json:"reason,omitempty"`}+// toolCallID returns the provider call id of a tool part. 1.x reports it as+// `callID` next to a part id in `id`; 2.x dropped `callID`, moved the part id+// to `partID`, and reports the call id as `id`. Reading only `callID` left+// every 2.x tool message with an empty CallID, so the transcript could not+// pair a call with its result.+func (p opencodeEventPart) toolCallID() string {+ if p.CallID != "" {+ return p.CallID+ }+ if p.Type == "tool" {+ return p.ID+ }+ return ""+}+type opencodePartMetadata struct {ProviderExecuted bool `json:"providerExecuted,omitempty"`}diff --git a/server/pkg/agent/opencode_acp.go b/server/pkg/agent/opencode_acp.gonew file mode 100644index 0000000000..38c1f99865--- /dev/null+++ b/server/pkg/agent/opencode_acp.go@@ -0,0 +1,837 @@+package agent++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "sync/atomic"+ "syscall"+ "time"+)++// OpenCode over ACP (`opencode acp`).+//+// `opencode run --format json` writes a tool_use event only once the tool has+// finished, with the call and its result in one line. The daemon therefore never+// sees a tool in flight on that transport, and a long silent tool — a build, a+// test suite, a delegated subagent — is judged by the short OpenCode idle window+// (DefaultOpenCodeIdleWatchdog, 10 min) instead of the tool budget, so healthy+// runs get force-stopped (GH #9614). Both majors stream tool starts on ACP+// instead: 1.x and 2.x send `tool_call` when the model emits the call and an+// `in_progress` `tool_call_update` carrying the real input the moment the tool+// starts executing. That second frame is where MessageToolUse is emitted (see+// hermesClient.toolInputArrivesInProgress).+//+// What differs between the majors on this transport, all verified against+// opencode-ai 1.19.4 and @opencode/cli 2.2.0 (handshake also on 1.15.0 and+// 2.0.0):+//+// - Model selection. Both advertise a `model` entry in configOptions and take+// session/set_config_option; 2.x has no session/set_model at all (-32601).+// Reasoning effort is the advertised `effort` option on both, so the 2.x+// `provider/model#variant` spelling is only split, never sent.+// - MCP. 1.x still honours OPENCODE_CONFIG_CONTENT, which carries every shape+// the OpenCode translator accepts, so it keeps that channel. 2.x ignores the+// env var; ACP session/new's `mcpServers` is the channel there, which keeps+// credentials in the process instead of in a file in the agent's workdir+// (the reason the run transport refuses MCP on 2.x).+// - Subagents. 2.x forwards a child session's updates into the parent with+// `_meta["opencode/child-session"]`. Its tool calls are kept (they are real+// work in flight); its text is dropped so the parent's output stays the+// parent's answer, matching the run transport.+// - Usage. The prompt result's usage is not a per-turn figure on either+// major: 1.x reports the last assistant message only, 2.x the session+// total. Usage is therefore summed from the session export, over the+// assistant messages this turn created (opencodeACPTurnUsage).+//+// Cancellation is `session/cancel`, which on both majors aborts the running+// tool and answers the prompt with stopReason "cancelled". On 2.x it is the+// only reliable stop: the ACP process hosts its server as a separate process+// group, so a group signal alone does not reach the tools.+//+// The run transport is kept as a fallback for everything this file cannot vouch+// for: custom runtime profiles, versions older than the ones checked, agents+// with custom_args (they are `opencode run` flags), and anyone who sets+// MULTICA_OPENCODE_TRANSPORT=run.++// opencodeTransportEnv selects the OpenCode transport. "run" forces the+// `opencode run --format json` path; anything else lets the backend choose.+// It is an operator setting read from the daemon's environment (the daemon+// strips MULTICA_* keys from agent custom_env); Config.Env is consulted first+// so tests can pin a transport per backend.+const opencodeTransportEnv = "MULTICA_OPENCODE_TRANSPORT"++// Oldest releases whose ACP surface (configOptions model + effort selectors,+// loadSession, session/cancel) matches what this file drives. 1.15.0 is the+// first 1.x release that advertises the effort option.+var (+ opencodeACPMinV1 = semver{Major: 1, Minor: 15, Patch: 0}+ opencodeACPMinV2 = semver{Major: 2, Minor: 0, Patch: 0}+)++// Timing knobs. Vars so tests can shorten them.+var (+ // opencodeACPCancelGrace bounds the wait for the prompt to answer after+ // session/cancel before the process is torn down regardless.+ opencodeACPCancelGrace = 5 * time.Second+ // opencodeACPExitGrace is how long the process gets to exit on its own+ // after stdin closes before it is signalled.+ opencodeACPExitGrace = 3 * time.Second+ // opencodeACPDrainGrace bounds the trailing-notification drain after the+ // prompt response, like the other ACP backends' reader drain.+ opencodeACPDrainGrace = 2 * time.Second+ // opencodeACPUsageTimeout bounds the post-run session export.+ opencodeACPUsageTimeout = 15 * time.Second+)++// opencodeUsesACP reports whether this run should use the ACP transport, and if+// not, why (for the log line).+func opencodeUsesACP(cfg Config, opts ExecOptions) (bool, string) {+ if strings.EqualFold(strings.TrimSpace(opencodeTransportSetting(cfg)), "run") {+ return false, opencodeTransportEnv + "=run"+ }+ // A custom profile wraps a binary this package did not choose, so its+ // version string does not establish which protocol it speaks — the same+ // rule opencodeUsesV2Contract applies.+ if !cfg.BuiltinRuntime || len(cfg.LaunchPrefix) != 0 {+ return false, "custom runtime profile"+ }+ version, err := parseSemver(strings.TrimSpace(cfg.CLIVersion))+ if err != nil {+ return false, "unknown OpenCode version"+ }+ switch {+ case version.Major == 1 && version.lessThan(opencodeACPMinV1):+ return false, "OpenCode older than " + fmt.Sprintf("%d.%d.%d", opencodeACPMinV1.Major, opencodeACPMinV1.Minor, opencodeACPMinV1.Patch)+ case version.Major < 1:+ return false, "OpenCode older than 1.x"+ case version.Major >= 2 && version.lessThan(opencodeACPMinV2):+ return false, "unrecognised OpenCode version"+ }+ // custom_args are `opencode run` flags (--agent, --attach, …); `opencode+ // acp` would reject or ignore them, so honour them on the transport they+ // were written for.+ if len(opts.CustomArgs) != 0 {+ return false, "agent has custom_args for `opencode run`"+ }+ return true, ""+}++func opencodeTransportSetting(cfg Config) string {+ if v, ok := cfg.Env[opencodeTransportEnv]; ok {+ return v+ }+ return os.Getenv(opencodeTransportEnv)+}++// opencodeACPToolName keeps OpenCode's own tool ids (bash, read, task, …) so+// the transcript reads the same as on the run transport. 2.x sends the id as+// `name`; 1.x's start frame sends it as `title`.+func opencodeACPToolName(name, title, kind string) string {+ if name = strings.TrimSpace(name); name != "" {+ return name+ }+ if title = strings.TrimSpace(title); title != "" {+ return title+ }+ return kind+}++// opencodeACPChildUpdate reports whether a session/update came from a 2.x+// subagent's child session rather than the session Multica prompted.+func opencodeACPChildUpdate(update json.RawMessage) bool {+ var u struct {+ Meta map[string]json.RawMessage `json:"_meta"`+ }+ if json.Unmarshal(update, &u) != nil {+ return false+ }+ _, ok := u.Meta["opencode/child-session"]+ return ok+}++// opencodeACPSplitModel splits a 2.x `provider/model#variant` selector. The+// pinned variant wins over the agent-level thinking level, as on the run+// transport (opencodeModelArg).+func opencodeACPSplitModel(model, thinkingLevel string) (string, string) {+ model = strings.TrimSpace(model)+ if base, variant, ok := strings.Cut(model, "#"); ok {+ if variant = strings.TrimSpace(variant); variant != "" {+ return strings.TrimSpace(base), variant+ }+ return strings.TrimSpace(base), thinkingLevel+ }+ return model, thinkingLevel+}++// opencodeACPSelectModel puts the session on model and returns the session's+// configOptions as they stand afterwards, which is what the effort option has+// to be read from: the effort vocabulary belongs to the current model.+func opencodeACPSelectModel(ctx context.Context, request acpRequestFn, sessionID, model string, sessionResult json.RawMessage) (json.RawMessage, error) {+ if model == "" {+ return sessionResult, nil+ }+ if _, ok := findACPConfigOption(sessionResult, "model"); !ok {+ // Not seen on any version this transport is enabled for; kept so an+ // unexpected build degrades to the older ACP model call.+ if _, err := request(ctx, "session/set_model", map[string]any{"sessionId": sessionID, "modelId": model}); err != nil {+ return nil, fmt.Errorf("select model %q: %w", model, err)+ }+ return nil, nil+ }+ result, err := request(ctx, "session/set_config_option", map[string]any{+ "sessionId": sessionID,+ "configId": "model",+ "value": model,+ })+ if err != nil {+ return nil, fmt.Errorf("select model %q: %w", model, err)+ }+ if current, ok := acpConfigOptionCurrentValue(result, "model"); ok && current != model {+ return nil, fmt.Errorf("select model %q: OpenCode kept the session on %q", model, current)+ }+ return result, nil+}++// opencodeACPMcpServers translates mcp_config for a 2.x ACP session. It goes+// through the OpenCode translator first so the accepted input shapes (including+// OpenCode-native `mcp` entries) and the validation are the same as on 1.x.+//+// Two OpenCode features have no ACP representation and fail the run rather+// than silently change what the agent gets: remote OAuth, and a bare+// {"enabled": …} override of a server the user configured elsewhere. A+// per-server timeout is dropped with a warning.+func opencodeACPMcpServers(raw json.RawMessage, cfg Config) ([]any, error) {+ if len(bytes.TrimSpace(raw)) == 0 {+ return []any{}, nil+ }+ servers, err := translateMCPConfigForOpenCode(raw)+ if err != nil {+ return nil, err+ }+ names := make([]string, 0, len(servers))+ for name := range servers {+ names = append(names, name)+ }+ sort.Strings(names)+ out := make([]any, 0, len(names))+ for _, name := range names {+ entry, _ := servers[name].(map[string]any)+ if enabled, ok := entry["enabled"].(bool); ok && !enabled {+ if _, typed := entry["type"]; typed {+ continue // a disabled server is simply not sent+ }+ }+ if _, ok := entry["timeout"]; ok && cfg.Logger != nil {+ cfg.Logger.Warn("opencode: MCP server timeout cannot be passed over ACP; using OpenCode's default", "server", name)+ }+ switch entry["type"] {+ case "local":+ command := stringsFromAny(entry["command"])+ if len(command) == 0 {+ return nil, fmt.Errorf("opencode mcp_config: server %q: local server missing `command`", name)+ }+ out = append(out, map[string]any{+ "name": name,+ "command": command[0],+ "args": append([]string{}, command[1:]...),+ "env": acpNameValues(entry["environment"]),+ })+ case "remote":+ if oauth, ok := entry["oauth"]; ok && oauth != false {+ return nil, fmt.Errorf("opencode mcp_config: server %q uses OAuth, which OpenCode 2.x cannot receive over ACP; use headers, an OpenCode 1.x runtime, or %s=run", name, opencodeTransportEnv)+ }+ url, _ := entry["url"].(string)+ out = append(out, map[string]any{+ "type": "http",+ "name": name,+ "url": url,+ "headers": acpNameValues(entry["headers"]),+ })+ default:+ return nil, fmt.Errorf("opencode mcp_config: server %q is an {\"enabled\": …} override, which OpenCode 2.x cannot receive over ACP", name)+ }+ }+ return out, nil+}++func stringsFromAny(v any) []string {+ switch items := v.(type) {+ case []string:+ return items+ case []any:+ out := make([]string, 0, len(items))+ for _, item := range items {+ s, ok := item.(string)+ if !ok {+ return nil+ }+ out = append(out, s)+ }+ return out+ }+ return nil+}++// acpNameValues turns a JSON object of strings into ACP's sorted+// [{name, value}] list.+func acpNameValues(v any) []map[string]any {+ m, _ := v.(map[string]any)+ keys := make([]string, 0, len(m))+ for k := range m {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ out := make([]map[string]any, 0, len(keys))+ for _, k := range keys {+ out = append(out, map[string]any{"name": k, "value": fmt.Sprint(m[k])})+ }+ return out+}++func (b *opencodeBackend) executeACP(ctx context.Context, execPath, prompt string, opts ExecOptions) (*Session, error) {+ usesV2 := opencodeUsesV2Contract(b.cfg)+ cwd := opts.Cwd+ if cwd == "" {+ cwd = "."+ }+ cwd, err := filepath.Abs(cwd)+ if err != nil {+ return nil, fmt.Errorf("opencode working directory: %w", err)+ }++ // 1.x: MCP rides OPENCODE_CONFIG_CONTENT exactly as on the run transport.+ // 2.x: MCP goes into session/new, and the env carries none.+ envOpts := opts+ mcpServers := []any{}+ if usesV2 {+ envOpts = ExecOptions{Cwd: opts.Cwd}+ if mcpServers, err = opencodeACPMcpServers(opts.McpConfig, b.cfg); err != nil {+ return nil, err+ }+ }+ env, err := openCodeEnvironment(b.cfg, envOpts)+ if err != nil {+ return nil, err+ }+ if opts.MaxTurns > 0 {+ b.cfg.Logger.Warn("opencode does not support --max-turns; ignoring", "maxTurns", opts.MaxTurns)+ }++ timeout := opts.Timeout+ runCtx, cancel := runContext(ctx, timeout)++ // The process runs on its own context so cancelling the task can go+ // through session/cancel first; procCancel is the last-resort group kill.+ procCtx, procCancel := context.WithCancel(context.Background())+ args := []string{"acp"}+ cmd := b.cfg.commandAt(execPath).exec(procCtx, args...)+ hideAgentWindow(cmd)+ cmd.WaitDelay = 5 * time.Second+ cmd.Dir = cwd+ cmd.Env = env+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args, trustAgentCommandPositional(0, "acp")))++ fail := func(err error) (*Session, error) {+ procCancel()+ cancel()+ return nil, err+ }+ stdout, err := cmd.StdoutPipe()+ if err != nil {+ return fail(fmt.Errorf("opencode stdout pipe: %w", err))+ }+ stdin, err := cmd.StdinPipe()+ if err != nil {+ return fail(fmt.Errorf("opencode stdin pipe: %w", err))+ }+ stderr, err := cmd.StderrPipe()+ if err != nil {+ return fail(fmt.Errorf("opencode stderr pipe: %w", err))+ }+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {+ return fail(fmt.Errorf("start opencode: %w", err))+ }+ b.cfg.Logger.Info("opencode acp started", "pid", cmd.Process.Pid, "cwd", cwd, "model", opts.Model)++ providerErr := newACPProviderErrorSniffer("opencode")+ stderrDone := make(chan struct{})+ go func() {+ defer close(stderrDone)+ _, _ = io.Copy(io.MultiWriter(newLogWriter(b.cfg.Logger, "[opencode:stderr] "), providerErr), stderr)+ }()++ msgCh := make(chan Message, 256)+ resCh := make(chan Result, 1)++ var streaming atomic.Bool+ var sawText, sawTool atomic.Bool+ var outputMu sync.Mutex+ var output strings.Builder+ activity := make(chan struct{}, 1)+ promptDone := make(chan hermesPromptResult, 1)++ c := &hermesClient{+ cfg: b.cfg,+ stdin: stdin,+ pending: make(map[int]*pendingRPC),+ pendingTools: make(map[string]*pendingToolCall),+ toolInputArrivesInProgress: true,+ toolOutputFromContent: true,+ toolName: opencodeACPToolName,+ // session/load replays the whole conversation as session/update;+ // only the turn this run prompts is this run's transcript.+ acceptNotification: func(string) bool { return streaming.Load() },+ acceptUpdate: func(updateType string, update json.RawMessage) bool {+ if updateType == "tool_call" || updateType == "tool_call_update" {+ return true+ }+ return !opencodeACPChildUpdate(update)+ },+ onActivity: func() {+ select {+ case activity <- struct{}{}:+ default:+ }+ },+ onMessage: func(msg Message) {+ if !streaming.Load() {+ return+ }+ switch msg.Type {+ case MessageText:+ sawText.Store(true)+ outputMu.Lock()+ output.WriteString(msg.Content)+ outputMu.Unlock()+ case MessageToolUse:+ sawTool.Store(true)+ }+ trySend(msgCh, msg)+ },+ onPromptDone: func(result hermesPromptResult) {+ select {+ case promptDone <- result:+ default:+ }+ },+ }++ readerDone := make(chan struct{})+ go func() {+ defer close(readerDone)+ scanner := newAgentStreamScanner(stdout)+ for scanner.Scan() {+ if line := strings.TrimSpace(scanner.Text()); line != "" {+ c.handleLine(line)+ }+ }+ c.closeAllPending(errors.New("opencode process exited"))+ }()++ // stop tears the process down exactly once. A graceful stop closes stdin+ // and lets OpenCode exit on EOF before signalling. A forced stop is for a+ // run that was cancelled or timed out without OpenCode answering: closing+ // stdin first releases a prompt write blocked on a full pipe (it holds the+ // client's write lock), and the group is signalled at once, so an+ // unresponsive runtime is gone within opencodeTerminateGrace instead of+ // being waited on.+ // promptSent flips once the whole prompt is in the pipe. Until then+ // OpenCode has not received the turn, so there is nothing for+ // session/cancel to stop.+ var promptSent atomic.Bool++ var stopOnce sync.Once+ stop := func(force bool) {+ stopOnce.Do(func() {+ _ = stdin.Close()+ if !force {+ select {+ case <-readerDone:+ case <-time.After(opencodeACPExitGrace):+ force = true+ }+ }+ if force {+ signalProcessGroup(cmd, syscall.SIGTERM)+ select {+ case <-readerDone:+ case <-time.After(opencodeTerminateGrace()):+ }+ }+ procCancel() // group SIGKILL; a no-op for a group that already exited+ _ = cmd.Wait()+ <-readerDone+ <-stderrDone+ releaseProcessGroup(cmd)+ })+ }++ go func() {+ defer close(msgCh)+ defer close(resCh)+ defer cancel()+ // Setup paths return early; a cancelled or timed-out setup is torn+ // down without the graceful wait.+ defer func() { stop(runCtx.Err() != nil) }()++ // Until the prompt is fully delivered there is no turn for+ // session/cancel to stop, and every request so far is a synchronous+ // write that checks its context only after the write returns. A+ // runtime that stops reading (a large session/new MCP payload, a+ // large prompt) would hold this goroutine in that write, so the+ // deferred stop above would never run. The watcher tears the process+ // down as soon as the run ends in that window; closing stdin is what+ // releases the blocked write. Once the prompt is delivered, the+ // cancel path below owns the shutdown.+ watcherDone := make(chan struct{})+ defer close(watcherDone)+ go func() {+ select {+ case <-runCtx.Done():+ if !promptSent.Load() {+ stop(true)+ }+ case <-watcherDone:+ }+ }()++ startTime := time.Now()+ result := func(status, errText, sessionID string, rejected bool) {+ resCh <- Result{Status: status, Error: errText, SessionID: sessionID, ResumeRejected: rejected, DurationMs: time.Since(startTime).Milliseconds()}+ }++ initResult, 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{+ "fs": map[string]any{"readTextFile": false, "writeTextFile": false},+ "terminal": false,+ },+ })+ if err != nil {+ status, errText, _ := classifyACPResumeFailure(runCtx, "opencode", "initialize", err, timeout, b.cfg.Logger)+ result(status, errText, "", false)+ return+ }+ mcpServers = filterACPMcpServersByCapability(mcpServers, extractACPMcpCapabilities(initResult), "opencode", b.cfg)++ var sessionID string+ var sessionResult json.RawMessage+ if opts.ResumeSessionID != "" {+ loaded, err := c.request(runCtx, "session/load", map[string]any{+ "cwd": cwd,+ "sessionId": opts.ResumeSessionID,+ "mcpServers": mcpServers,+ })+ if err != nil {+ status, errText, rejected := classifyACPResumeFailure(runCtx, "opencode", "session/load", err, timeout, b.cfg.Logger)+ result(status, errText, "", rejected)+ return+ }+ var changed bool+ sessionID, changed = resolveResumedSessionID(opts.ResumeSessionID, loaded)+ if changed {+ b.cfg.Logger.Warn("opencode returned a different session id on resume; continuing with the new id",+ "requested", opts.ResumeSessionID, "actual", sessionID)+ }+ sessionResult = loaded+ } else {+ created, err := c.request(runCtx, "session/new", map[string]any{+ "cwd": cwd,+ "mcpServers": mcpServers,+ })+ if err != nil {+ status, errText, _ := classifyACPResumeFailure(runCtx, "opencode", "session/new", err, timeout, b.cfg.Logger)+ result(status, errText, "", false)+ return+ }+ if sessionID = extractACPSessionID(created); sessionID == "" {+ result("failed", "opencode session/new returned no session ID", "", false)+ return+ }+ sessionResult = created+ }+ c.sessionID = sessionID++ model, level := opencodeACPSplitModel(opts.Model, opts.ThinkingLevel)+ options, err := opencodeACPSelectModel(runCtx, c.request, sessionID, model, sessionResult)+ if err != nil {+ status, errText, _ := classifyACPResumeFailure(runCtx, "opencode", "model selection", err, timeout, b.cfg.Logger)+ keep := sessionID+ if setupFailureWithholdsSessionID(opts) {+ keep = ""+ }+ result(status, errText, keep, false)+ return+ }+ if options != nil {+ applyACPEffortOption(runCtx, c.request, "opencode", b.cfg.Logger, sessionID, options, level, true)+ } else if level != "" {+ b.cfg.Logger.Warn("opencode session advertises no configuration after model selection; ignoring thinking level", "thinkingLevel", level)+ }++ b.cfg.Logger.Info("opencode session ready", "session_id", sessionID, "resumed", opts.ResumeSessionID != "")+ trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})++ // OpenCode reads the runtime brief from the AGENTS.md the daemon writes+ // into the workdir, so SystemPrompt is not prepended — same as the run+ // transport (MUL-5392).+ streaming.Store(true)+ turnStart := time.Now()+ type promptOutcome struct{ err error }+ promptCh := make(chan promptOutcome, 1)+ go func() {+ _, err := c.requestAndNotifySent(context.Background(), "session/prompt", map[string]any{+ "sessionId": sessionID,+ "prompt": []map[string]any{{"type": "text", "text": prompt}},+ }, func() { promptSent.Store(true) })+ promptCh <- promptOutcome{err: err}+ }()++ finalStatus := "completed"+ var finalError string+ var promptErr error+ answered := false+ select {+ case out := <-promptCh:+ promptErr, answered = out.err, true+ case <-runCtx.Done():+ if !promptSent.Load() {+ b.cfg.Logger.Warn("opencode: run ended before the prompt was delivered; stopping the process")+ break+ }+ // Ask OpenCode to stop the turn; it aborts the running tool and+ // answers the prompt. The write runs on its own goroutine so a+ // stalled pipe cannot hold the teardown, and the grace starts now.+ go func() {+ if err := opencodeACPNotify(c, "session/cancel", map[string]any{"sessionId": sessionID}); err != nil {+ b.cfg.Logger.Warn("opencode: session/cancel could not be sent", "error", err)+ }+ }()+ select {+ case out := <-promptCh:+ promptErr, answered = out.err, true+ case <-time.After(opencodeACPCancelGrace):+ b.cfg.Logger.Warn("opencode did not answer session/cancel in time; stopping the process", "grace", opencodeACPCancelGrace.String())+ }+ }++ var pr hermesPromptResult+ havePrompt := false+ if answered && promptErr == nil {+ select {+ case pr = <-promptDone:+ havePrompt = true+ default:+ }+ }++ switch {+ case runCtx.Err() == context.DeadlineExceeded:+ finalStatus, finalError = "timeout", fmt.Sprintf("opencode timed out after %s", timeout)+ case runCtx.Err() == context.Canceled:+ finalStatus, finalError = "aborted", "execution cancelled"+ case promptErr != nil:+ finalStatus, finalError = "failed", fmt.Sprintf("opencode session/prompt failed: %v", promptErr)+ case havePrompt:+ switch pr.stopReason {+ case "", "end_turn":+ case "cancelled":+ finalStatus, finalError = "aborted", "opencode cancelled the turn"+ case "max_tokens":+ finalStatus, finalError = "failed", "opencode stopped: the model hit its output length limit"+ case "refusal":+ finalStatus, finalError = "failed", "opencode stopped: the provider refused the request"+ default:+ finalStatus, finalError = "failed", "opencode stopped: "+pr.stopReason+ }+ }+ if answered && runCtx.Err() == nil {+ waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, opencodeACPDrainGrace)+ }+ streaming.Store(false)+ // A turn OpenCode never answered is forced down; an answered one,+ // including an acknowledged cancel, exits gracefully.+ stop(!answered)+ providerErr.Finalize()++ outputMu.Lock()+ finalOutput := output.String()+ outputMu.Unlock()+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)++ usage, usageErr := opencodeACPTurnUsage(b.cfg, execPath, env, cwd, sessionID, turnStart, usesV2)+ if usageErr != nil {+ usage = TokenUsage{}+ // Fall back to what the prompt reported only where that figure is+ // not an overcount: 1.x reports one message (an undercount), and a+ // fresh 2.x session's total is this turn.+ if havePrompt && (!usesV2 || opts.ResumeSessionID == "") {+ usage = pr.usage.TokenUsage+ usage.CostUSDTicks = 0+ }+ b.cfg.Logger.Warn("opencode: could not read this turn's token usage from the session export", "error", usageErr, "fallback", acpTokenUsagePresent(usage))+ }++ // The run transport's empty-step guard (#6522): a turn that closes+ // cleanly with no text, no tool call and no usage at all never reached+ // the provider, and must not be reported as a success.+ if finalStatus == "completed" && usageErr == nil && !sawText.Load() && !sawTool.Load() && !acpTokenUsagePresent(usage) {+ finalStatus = "failed"+ finalError = "opencode turn ended with no text, no tool call and no reported usage — the provider produced nothing"+ }++ var usageMap map[string]TokenUsage+ if acpTokenUsagePresent(usage) {+ name := opts.Model+ if name == "" {+ name = "unknown"+ }+ usageMap = map[string]TokenUsage{name: usage}+ }+ duration := time.Since(startTime)+ b.cfg.Logger.Info("opencode finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())+ resCh <- Result{+ Status: finalStatus,+ Output: finalOutput,+ Error: finalError,+ DurationMs: duration.Milliseconds(),+ SessionID: sessionID,+ Usage: usageMap,+ }+ }()++ return &Session{Messages: msgCh, Result: resCh}, nil+}++// opencodeACPNotify writes a JSON-RPC notification (no id, no response).+func opencodeACPNotify(c *hermesClient, method string, params any) error {+ data, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": method, "params": params})+ if err != nil {+ return err+ }+ return c.writeLine(append(data, '\n'))+}++// opencodeACPTurnUsage sums the token usage of the assistant messages this turn+// created, read from the session export after the process has exited.+//+// Each OpenCode step is its own assistant message with its own provider call,+// so the turn's usage is their sum — the same figure the run transport adds up+// from step_finish events. The turn's messages are the ones created at or after+// turnStart; the export's timestamps come from the same host clock.+func opencodeACPTurnUsage(cfg Config, execPath string, env []string, cwd, sessionID string, turnStart time.Time, usesV2 bool) (TokenUsage, error) {+ if sessionID == "" || strings.HasPrefix(sessionID, "-") {+ return TokenUsage{}, errors.New("no session id")+ }+ ctx, cancel := context.WithTimeout(context.Background(), opencodeACPUsageTimeout)+ defer cancel()+ args := []string{"export", sessionID}+ if usesV2 {+ // --standalone keeps the export off the resident background service:+ // this run never started one, and should not leave one behind.+ args = []string{"session", "export", sessionID, "--standalone"}+ }+ run := func(args []string) ([]byte, error) {+ cmd := cfg.commandAt(execPath).exec(ctx, args...)+ hideAgentWindow(cmd)+ cmd.Dir, cmd.Env = cwd, env+ cmd.Stderr = &tailBuffer{max: 4096}+ limited := &limitedBuffer{max: openCodeClockExportMaxBytes}+ cmd.Stdout = limited+ err := runOwned(cmd, cfg.Logger)+ if limited.overflow {+ return nil, errors.New("session export exceeds the size limit")+ }+ return limited.buf.Bytes(), err+ }+ // --sanitize redacts message text, which this never needs. Older CLIs+ // lack the flag; retry without it.+ data, err := run(append(args, "--sanitize"))+ if err != nil {+ data, err = run(args)+ }+ if err != nil {+ return TokenUsage{}, fmt.Errorf("session export: %w", err)+ }+ return opencodeExportTurnUsage(data, turnStart.UnixMilli(), opencodeSeparatesReasoning(cfg))+}++// opencodeExportTurnUsage reads both export shapes: 1.x nests each message's+// metadata under `info` with a `role`; 2.x flattens it and names the kind+// `type`.+func opencodeExportTurnUsage(data []byte, sinceMs int64, separateReasoning bool) (TokenUsage, error) {+ type msgTime struct {+ Created int64 `json:"created"`+ }+ type meta struct {+ Role string `json:"role"`+ Type string `json:"type"`+ Time msgTime `json:"time"`+ Tokens *opencodeTokens `json:"tokens"`+ }+ var export struct {+ Messages []struct {+ meta+ Info *meta `json:"info"`+ } `json:"messages"`+ }+ start := bytes.IndexByte(data, '{')+ if start < 0 {+ return TokenUsage{}, errors.New("session export is not JSON")+ }+ if err := json.Unmarshal(data[start:], &export); err != nil {+ return TokenUsage{}, fmt.Errorf("parse session export: %w", err)+ }+ var usage TokenUsage+ for _, m := range export.Messages {+ info := m.meta+ if m.Info != nil {+ info = *m.Info+ }+ if info.Role != "assistant" && info.Type != "assistant" {+ continue+ }+ if info.Time.Created < sinceMs || info.Tokens == nil {+ continue+ }+ t := info.Tokens+ usage.InputTokens += t.Input+ usage.OutputTokens += t.Output+ if separateReasoning {+ usage.OutputTokens += t.Reasoning+ }+ if t.Cache != nil {+ usage.CacheReadTokens += t.Cache.Read+ usage.CacheWriteTokens += t.Cache.Write+ }+ }+ return usage, nil+}++// limitedBuffer keeps at most max bytes and records whether more arrived.+type limitedBuffer struct {+ buf bytes.Buffer+ max int+ overflow bool+}++func (l *limitedBuffer) Write(p []byte) (int, error) {+ if room := l.max - l.buf.Len(); room < len(p) {+ l.overflow = true+ if room > 0 {+ l.buf.Write(p[:room])+ }+ return len(p), nil+ }+ return l.buf.Write(p)+}diff --git a/server/pkg/agent/opencode_acp_test.go b/server/pkg/agent/opencode_acp_test.gonew file mode 100644index 0000000000..f607d1e4d1--- /dev/null+++ b/server/pkg/agent/opencode_acp_test.go@@ -0,0 +1,160 @@+package agent++import (+ "encoding/json"+ "log/slog"+ "strings"+ "testing"+)++func TestOpencodeUsesACP(t *testing.T) {+ t.Parallel()+ cases := []struct {+ name string+ cfg Config+ opts ExecOptions+ want bool+ }{+ {"1.x current", Config{BuiltinRuntime: true, CLIVersion: "1.19.4"}, ExecOptions{}, true},+ {"1.x first with effort option", Config{BuiltinRuntime: true, CLIVersion: "1.15.0"}, ExecOptions{}, true},+ {"1.x too old", Config{BuiltinRuntime: true, CLIVersion: "1.14.9"}, ExecOptions{}, false},+ {"2.x as reported", Config{BuiltinRuntime: true, CLIVersion: "opencode v2.2.0"}, ExecOptions{}, true},+ {"2.0.0", Config{BuiltinRuntime: true, CLIVersion: "opencode v2.0.0"}, ExecOptions{}, true},+ {"unknown version", Config{BuiltinRuntime: true}, ExecOptions{}, false},+ {"custom profile", Config{BuiltinRuntime: false, CLIVersion: "1.19.4"}, ExecOptions{}, false},+ {"launch prefix", Config{BuiltinRuntime: true, CLIVersion: "1.19.4", LaunchPrefix: []string{"--x"}}, ExecOptions{}, false},+ {"custom_args are run flags", Config{BuiltinRuntime: true, CLIVersion: "1.19.4"}, ExecOptions{CustomArgs: []string{"--agent", "plan"}}, false},+ {"forced run", Config{BuiltinRuntime: true, CLIVersion: "1.19.4", Env: map[string]string{opencodeTransportEnv: "RUN"}}, ExecOptions{}, false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got, reason := opencodeUsesACP(tc.cfg, tc.opts); got != tc.want {+ t.Fatalf("opencodeUsesACP = %v (%s), want %v", got, reason, tc.want)+ }+ })+ }+}++func TestOpencodeACPSplitModel(t *testing.T) {+ t.Parallel()+ cases := []struct{ model, level, wantModel, wantLevel string }{+ {"openai/gpt-5", "high", "openai/gpt-5", "high"},+ {"openai/gpt-5#max", "high", "openai/gpt-5", "max"},+ {"openai/gpt-5#", "high", "openai/gpt-5", "high"},+ {"", "high", "", "high"},+ }+ for _, tc := range cases {+ m, l := opencodeACPSplitModel(tc.model, tc.level)+ if m != tc.wantModel || l != tc.wantLevel {+ t.Fatalf("split(%q,%q) = %q,%q want %q,%q", tc.model, tc.level, m, l, tc.wantModel, tc.wantLevel)+ }+ }+}++func TestOpencodeACPMcpServers(t *testing.T) {+ t.Parallel()+ cfg := Config{Logger: slog.Default()}+ raw := json.RawMessage(`{"mcpServers":{+ "local":{"command":"node","args":["s.js"],"env":{"B":"2","A":"1"}},+ "remote":{"url":"https://example.invalid/mcp","headers":{"Authorization":"Bearer x"}},+ "off":{"command":"x","enabled":false}+ }}`)+ got, err := opencodeACPMcpServers(raw, cfg)+ if err != nil {+ t.Fatalf("translate: %v", err)+ }+ data, _ := json.Marshal(got)+ want := `[{"args":["s.js"],"command":"node","env":[{"name":"A","value":"1"},{"name":"B","value":"2"}],"name":"local"},` ++ `{"headers":[{"name":"Authorization","value":"Bearer x"}],"name":"remote","type":"http","url":"https://example.invalid/mcp"}]`+ if string(data) != want {+ t.Fatalf("servers =\n%s\nwant\n%s", data, want)+ }++ if _, err := opencodeACPMcpServers(json.RawMessage(`{"mcp":{"r":{"type":"remote","url":"https://x","oauth":{"clientId":"c"}}}}`), cfg); err == nil || !strings.Contains(err.Error(), "OAuth") {+ t.Fatalf("OAuth server must be refused, got %v", err)+ }+ if _, err := opencodeACPMcpServers(json.RawMessage(`{"mcp":{"inherited":{"enabled":false}}}`), cfg); err == nil {+ t.Fatal("bare enabled override must be refused")+ }+ if got, err := opencodeACPMcpServers(nil, cfg); err != nil || len(got) != 0 {+ t.Fatalf("empty config = %v, %v", got, err)+ }+}++func TestOpencodeExportTurnUsage(t *testing.T) {+ t.Parallel()+ v1 := `{"info":{"id":"ses"},"messages":[+ {"info":{"role":"user","time":{"created":200}}},+ {"info":{"role":"assistant","time":{"created":100},"tokens":{"input":1000,"output":1000,"reasoning":0,"cache":{"read":0,"write":0}}}},+ {"info":{"role":"assistant","time":{"created":201},"tokens":{"input":10,"output":5,"reasoning":3,"cache":{"read":7,"write":1}}}},+ {"info":{"role":"assistant","time":{"created":300},"tokens":{"input":20,"output":6,"reasoning":4,"cache":{"read":8,"write":0}}}}]}`+ got, err := opencodeExportTurnUsage([]byte(v1), 200, true)+ if err != nil {+ t.Fatal(err)+ }+ if want := (TokenUsage{InputTokens: 30, OutputTokens: 18, CacheReadTokens: 15, CacheWriteTokens: 1}); got != want {+ t.Fatalf("1.x usage = %+v want %+v", got, want)+ }++ // 2.x flattens message metadata and may print a banner before the JSON.+ v2 := "warning: banner\n" + `{"info":{"id":"ses"},"messages":[+ {"type":"model-switched","time":{"created":250}},+ {"type":"assistant","time":{"created":250},"tokens":{"input":9182,"output":55,"reasoning":256,"cache":{"read":3,"write":0}}},+ {"type":"assistant","time":{"created":260},"tokens":{"input":115,"output":8,"reasoning":17,"cache":{"read":9187,"write":0}}}]}`+ got, err = opencodeExportTurnUsage([]byte(v2), 200, false)+ if err != nil {+ t.Fatal(err)+ }+ if want := (TokenUsage{InputTokens: 9297, OutputTokens: 63, CacheReadTokens: 9190}); got != want {+ t.Fatalf("2.x usage = %+v want %+v", got, want)+ }++ if _, err := opencodeExportTurnUsage([]byte("not json"), 0, false); err == nil {+ t.Fatal("expected a parse error")+ }+}++// The run transport's 2.x tool_use part carries the call id as `id` (with the+// part id moved to `partID`); 1.x uses `callID`. Both must reach CallID.+func TestOpencodeToolUseCallIDBothMajors(t *testing.T) {+ t.Parallel()+ lines := map[string]string{+ "1.x": `{"type":"tool_use","sessionID":"s","part":{"id":"prt_1","type":"tool","tool":"task","callID":"call-v1","state":{"status":"completed","input":{},"output":"ok"}}}`,+ "2.x": `{"type":"tool_use","sessionID":"s","part":{"partID":"prt_2","type":"tool","id":"call-v2","tool":"subagent","state":{"status":"completed","input":{},"output":"ok"}}}`,+ }+ want := map[string]string{"1.x": "call-v1", "2.x": "call-v2"}+ for name, line := range lines {+ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}}+ ch := make(chan Message, 8)+ b.processEvents(strings.NewReader(line+"\n"), ch)+ close(ch)+ var got []Message+ for m := range ch {+ got = append(got, m)+ }+ if len(got) != 2 || got[0].Type != MessageToolUse || got[1].Type != MessageToolResult {+ t.Fatalf("%s: messages = %+v", name, got)+ }+ if got[0].CallID != want[name] || got[1].CallID != want[name] {+ t.Fatalf("%s: call ids = %q/%q, want %q", name, got[0].CallID, got[1].CallID, want[name])+ }+ }+}++// A non-tool part's `id` is a part id, never a call id.+func TestOpencodeToolCallIDIgnoresNonToolParts(t *testing.T) {+ t.Parallel()+ if got := (opencodeEventPart{ID: "prt_x", Type: "text"}).toolCallID(); got != "" {+ t.Fatalf("toolCallID = %q, want empty", got)+ }+}++func TestOpencodeACPChildUpdate(t *testing.T) {+ t.Parallel()+ if !opencodeACPChildUpdate(json.RawMessage(`{"sessionUpdate":"agent_message_chunk","_meta":{"opencode/child-session":{"id":"ses_c"}}}`)) {+ t.Fatal("child update not recognised")+ }+ if opencodeACPChildUpdate(json.RawMessage(`{"sessionUpdate":"agent_message_chunk","_meta":{}}`)) {+ t.Fatal("parent update recognised as child")+ }+}diff --git a/server/pkg/agent/opencode_acp_unix_test.go b/server/pkg/agent/opencode_acp_unix_test.gonew file mode 100644index 0000000000..938b737435--- /dev/null+++ b/server/pkg/agent/opencode_acp_unix_test.go@@ -0,0 +1,269 @@+//go:build unix++package agent++import (+ "context"+ "encoding/json"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// fakeOpencodeACPScript speaks enough of `opencode acp` to drive executeACP,+// with the frame shapes recorded from opencode-ai 1.19.4 and @opencode/cli+// 2.2.0. FAKE_MODE=cancel holds the prompt open until session/cancel arrives.+// `export` / `session export` print a transcript whose old message (created 1)+// must not be billed to this turn.+func fakeOpencodeACPScript() string {+ return `#!/bin/sh+if [ "$1" = "export" ] || [ "$1" = "session" ]; then+ printf '%s\n' "$*" >> "$FAKE_LOG.export"+ printf '%s' '{"info":{"id":"ses_fake"},"messages":[{"info":{"role":"assistant","time":{"created":1},"tokens":{"input":999,"output":999,"cache":{"read":0,"write":0}}}},{"info":{"role":"assistant","time":{"created":9999999999999},"tokens":{"input":40,"output":7,"cache":{"read":3,"write":0}}}}]}'+ exit 0+fi+prompt_id=""+while IFS= read -r line; do+ printf '%s\n' "$line" >> "$FAKE_LOG"+ id=$(printf '%s' "$line" | sed -n 's/^{"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ if [ "$FAKE_MODE" = "stall-setup" ]; then+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ exec sleep 60+ fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false}}}}\n' "$id" ;;+ *'"method":"session/new"'*|*'"method":"session/load"'*)+ if [ "$FAKE_MODE" = "stall" ]; then+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake"}}\n' "$id"+ exec sleep 60+ fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake","configOptions":[{"id":"model","category":"model","type":"select","currentValue":"opencode/default","options":[{"value":"opencode/default"},{"value":"opencode/picked"}]}]}}\n' "$id" ;;+ *'"method":"session/set_config_option"'*'"configId":"model"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[{"id":"model","category":"model","currentValue":"opencode/picked","options":[{"value":"opencode/picked"}]},{"id":"effort","category":"thought_level","currentValue":"default","options":[{"value":"high"},{"value":"default"}]}]}}\n' "$id" ;;+ *'"method":"session/set_config_option"'*'"configId":"effort"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[{"id":"effort","category":"thought_level","currentValue":"high","options":[{"value":"high"},{"value":"default"}]}]}}\n' "$id" ;;+ *'"method":"session/prompt"'*)+ prompt_id=$id+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"tool_call","toolCallId":"call-1","name":"bash","title":"bash","kind":"execute","status":"pending","rawInput":{"cwd":"/w"}}}}'+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1","status":"in_progress","kind":"execute","title":"sleep 1","rawInput":{"command":"sleep 1","cwd":"/w"}}}}'+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1","status":"in_progress","kind":"execute","title":"sleep 1","rawInput":{"command":"sleep 1","cwd":"/w"}}}}'+ if [ "$FAKE_MODE" = "cancel" ]; then continue; fi+ if [ "$FAKE_MODE" = "ignore-cancel" ]; then exec sleep 60; fi+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CHILD-TEXT"},"_meta":{"opencode/child-session":{"id":"ses_child","parentID":"ses_fake"}}}}}'+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1","status":"completed","content":[{"type":"content","content":{"type":"text","text":"slept"}}],"rawOutput":{"metadata":{"exit":0}}}}}'+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"parent answer"}}}}'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":1}}}\n' "$id" ;;+ *'"method":"session/cancel"'*)+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_fake","update":{"sessionUpdate":"tool_call_update","toolCallId":"call-1","status":"failed","content":[{"type":"content","content":{"type":"text","text":"Tool execution interrupted"}}]}}}'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"cancelled"}}\n' "$prompt_id" ;;+ esac+done+`+}++func newFakeOpencodeACP(t *testing.T, version, mode string) (Backend, string) {+ t.Helper()+ dir := t.TempDir()+ bin := filepath.Join(dir, "opencode")+ writeTestExecutable(t, bin, []byte(fakeOpencodeACPScript()))+ logPath := filepath.Join(dir, "requests.log")+ backend, err := New("opencode", Config{+ ExecutablePath: bin,+ CLIVersion: version,+ BuiltinRuntime: true,+ Logger: slog.Default(),+ Env: map[string]string{"FAKE_LOG": logPath, "FAKE_MODE": mode},+ })+ if err != nil {+ t.Fatalf("new opencode backend: %v", err)+ }+ return backend, logPath+}++func TestOpencodeACPStreamsToolStartAndSumsTurnUsage(t *testing.T) {+ t.Parallel()+ for _, version := range []string{"1.19.4", "opencode v2.2.0"} {+ t.Run(version, func(t *testing.T) {+ t.Parallel()+ backend, logPath := newFakeOpencodeACP(t, version, "")+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ mcp := `{"mcpServers":{"probe":{"command":"node","args":["s.js"]}}}`+ session, err := backend.Execute(ctx, "do it", ExecOptions{+ Cwd: t.TempDir(),+ Model: "opencode/picked",+ ThinkingLevel: "high",+ McpConfig: []byte(mcp),+ Timeout: 15 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ var msgs []Message+ for m := range session.Messages {+ msgs = append(msgs, m)+ }+ res := <-session.Result+ if res.Status != "completed" || res.SessionID != "ses_fake" {+ t.Fatalf("result = %+v", res)+ }+ if res.Output != "parent answer" {+ t.Fatalf("output = %q: a subagent's text must not reach the parent's output", res.Output)+ }+ // The tool is announced once, from the in_progress frame, with the+ // real input rather than the start frame's placeholder.+ var uses, results []Message+ for _, m := range msgs {+ switch m.Type {+ case MessageToolUse:+ uses = append(uses, m)+ case MessageToolResult:+ results = append(results, m)+ }+ }+ if len(uses) != 1 || uses[0].Tool != "bash" || uses[0].CallID != "call-1" || uses[0].Input["command"] != "sleep 1" {+ t.Fatalf("tool uses = %+v", uses)+ }+ if len(results) != 1 || results[0].CallID != "call-1" || results[0].Output != "slept" {+ t.Fatalf("tool results = %+v", results)+ }+ // Billed from the export, this turn's messages only.+ if u := res.Usage["opencode/picked"]; u.InputTokens != 40 || u.OutputTokens != 7 || u.CacheReadTokens != 3 {+ t.Fatalf("usage = %+v", res.Usage)+ }++ raw, err := os.ReadFile(logPath)+ if err != nil {+ t.Fatal(err)+ }+ requests := string(raw)+ for _, want := range []string{`"configId":"model","sessionId":"ses_fake","value":"opencode/picked"`, `"configId":"effort","sessionId":"ses_fake","value":"high"`} {+ if !strings.Contains(requests, want) {+ t.Fatalf("missing request %s in:\n%s", want, requests)+ }+ }+ // 2.x receives MCP in session/new; 1.x keeps OPENCODE_CONFIG_CONTENT.+ newHasMCP := strings.Contains(requests, `"name":"probe"`)+ if newHasMCP != (version != "1.19.4") {+ t.Fatalf("session/new carried MCP = %v for %s:\n%s", newHasMCP, version, requests)+ }+ export, _ := os.ReadFile(logPath + ".export")+ if version == "1.19.4" && !strings.HasPrefix(string(export), "export ses_fake") ||+ version != "1.19.4" && !strings.Contains(string(export), "session export ses_fake --standalone") {+ t.Fatalf("export argv = %q", export)+ }+ })+ }+}++func TestOpencodeACPCancelSendsSessionCancel(t *testing.T) {+ t.Parallel()+ backend, logPath := newFakeOpencodeACP(t, "opencode v2.2.0", "cancel")+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session, err := backend.Execute(ctx, "do it", ExecOptions{Cwd: t.TempDir(), Timeout: 20 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for m := range session.Messages {+ if m.Type == MessageToolUse {+ cancel()+ }+ }+ }()+ select {+ case res := <-session.Result:+ if res.Status != "aborted" {+ t.Fatalf("result = %+v", res)+ }+ case <-time.After(15 * time.Second):+ t.Fatal("cancelled run did not finish")+ }+ raw, _ := os.ReadFile(logPath)+ if !strings.Contains(string(raw), `"method":"session/cancel"`) {+ t.Fatalf("session/cancel was not sent:\n%s", raw)+ }+}++// A runtime that stops reading stdin mid-prompt must not outlive the run's+// timeout: the blocked prompt write holds the client's write lock, so the+// teardown cannot wait on a session/cancel write (review of #9619).+func TestOpencodeACPTimeoutTearsDownStalledPromptWrite(t *testing.T) {+ t.Parallel()+ backend, _ := newFakeOpencodeACP(t, "1.19.4", "stall")+ started := time.Now()+ session, err := backend.Execute(context.Background(), strings.Repeat("x", 1<<20), ExecOptions{Cwd: t.TempDir(), Timeout: time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ for range session.Messages {+ }+ res := <-session.Result+ if elapsed := time.Since(started); elapsed > 4*time.Second {+ t.Fatalf("teardown took %s; want it bounded by the timeout, not the runtime's own exit", elapsed)+ }+ if res.Status != "timeout" {+ t.Fatalf("result = %+v", res)+ }+}++// A runtime that received the prompt but ignores session/cancel is forced+// down after opencodeACPCancelGrace.+func TestOpencodeACPCancelIgnoredIsForced(t *testing.T) {+ t.Parallel()+ backend, _ := newFakeOpencodeACP(t, "opencode v2.2.0", "ignore-cancel")+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session, err := backend.Execute(ctx, "do it", ExecOptions{Cwd: t.TempDir(), Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ var cancelledAt time.Time+ go func() {+ for m := range session.Messages {+ if m.Type == MessageToolUse && cancelledAt.IsZero() {+ cancelledAt = time.Now()+ cancel()+ }+ }+ }()+ select {+ case res := <-session.Result:+ if res.Status != "aborted" {+ t.Fatalf("result = %+v", res)+ }+ case <-time.After(opencodeACPCancelGrace + 6*time.Second):+ t.Fatal("cancelled run whose runtime ignored session/cancel was not torn down")+ }+}++// The same bound must hold before the prompt: a runtime that stops reading+// after initialize leaves session/new blocked in its stdin write (a large MCP+// payload fills the pipe), and the request checks its context only after the+// write returns (second review of #9619).+func TestOpencodeACPTimeoutTearsDownStalledSetupWrite(t *testing.T) {+ t.Parallel()+ backend, _ := newFakeOpencodeACP(t, "opencode v2.2.0", "stall-setup")+ mcp, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{"probe": map[string]any{+ "command": "node", "args": []string{"probe.js"}, "env": map[string]string{"BIG": strings.Repeat("x", 256<<10)},+ }}})+ started := time.Now()+ session, err := backend.Execute(context.Background(), "hello", ExecOptions{Cwd: t.TempDir(), McpConfig: mcp, Timeout: time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ for range session.Messages {+ }+ res := <-session.Result+ if elapsed := time.Since(started); elapsed > 4*time.Second {+ t.Fatalf("teardown took %s; want it bounded by the timeout, not the runtime's own exit", elapsed)+ }+ if res.Status != "timeout" {+ t.Fatalf("result = %+v", res)+ }+}diff --git a/server/pkg/agent/opencode_usage_test.go b/server/pkg/agent/opencode_usage_test.goindex 715cb9444e..2ee66403c2 100644--- a/server/pkg/agent/opencode_usage_test.go+++ b/server/pkg/agent/opencode_usage_test.go@@ -86,7 +86,7 @@ func TestOpencodeExecuteRetainsReasoningOnlyUsage(t *testing.T) {CLIVersion: "1.18.31",BuiltinRuntime: true,Logger: slog.Default(),- Env: map[string]string{+ Env: map[string]string{opencodeTransportEnv: "run",opencodeStdinHelperEnv: "1",opencodeStdinHelperArgvFile: filepath.Join(dir, "argv.txt"),opencodeStdinHelperInFile: filepath.Join(dir, "stdin.txt"),diff --git a/server/pkg/agent/opencode_v2.go b/server/pkg/agent/opencode_v2.goindex f7c6f34ebc..9000ba79de 100644--- a/server/pkg/agent/opencode_v2.go+++ b/server/pkg/agent/opencode_v2.go@@ -97,6 +97,10 @@ func opencodeModelArg(model, thinkingLevel string) (string, bool) {// ErrOpenCodeV2MCPUnsupported reports that the MCP servers Multica manages for// a task cannot be delivered to an OpenCode 2.x runtime yet.//+// This applies to the `opencode run` transport only. The ACP transport, which+// built-in 2.x runtimes use by default (opencode_acp.go), passes MCP servers in+// ACP session/new and never needs the workdir file.+//// The message deliberately does not name agent.mcp_config. ExecOptions.McpConfig// is the *composed* set, and only one of its sources is the agent's own column:// the daemon also folds in the workspace MCP servers bound to the agent (atdiff --git a/server/pkg/agent/opencode_v2_terminal_test.go b/server/pkg/agent/opencode_v2_terminal_test.goindex 627e3f7c16..be58e47f70 100644--- a/server/pkg/agent/opencode_v2_terminal_test.go+++ b/server/pkg/agent/opencode_v2_terminal_test.go@@ -23,7 +23,7 @@ const ()func v2TermConfig() Config {- return Config{Logger: slog.Default(), BuiltinRuntime: true, CLIVersion: "opencode v2.1.3"}+ return Config{Logger: slog.Default(), BuiltinRuntime: true, CLIVersion: "opencode v2.1.3", Env: map[string]string{opencodeTransportEnv: "run"}}}func runV2TermStream(t *testing.T, cfg Config, lines ...string) eventResult {diff --git a/server/pkg/agent/opencode_v2_terminal_unix_test.go b/server/pkg/agent/opencode_v2_terminal_unix_test.goindex 4d6c21f460..b7c20bb78b 100644--- a/server/pkg/agent/opencode_v2_terminal_unix_test.go+++ b/server/pkg/agent/opencode_v2_terminal_unix_test.go@@ -49,6 +49,7 @@ func TestOpencodeV2ExecuteExitIsTerminal(t *testing.T) {ExecutablePath: fakePath,CLIVersion: "opencode v2.1.3",BuiltinRuntime: true,+ Env: map[string]string{opencodeTransportEnv: "run"},Logger: slog.Default(),})if err != nil {diff --git a/server/pkg/agent/opencode_v2_test.go b/server/pkg/agent/opencode_v2_test.goindex 2a22caeac7..e0cc27f23f 100644--- a/server/pkg/agent/opencode_v2_test.go+++ b/server/pkg/agent/opencode_v2_test.go@@ -143,6 +143,7 @@ func TestOpencodeV2ExecuteRefusesMCPConfig(t *testing.T) {ExecutablePath: fakePath,CLIVersion: "opencode v2.0.10",BuiltinRuntime: true,+ Env: map[string]string{opencodeTransportEnv: "run"},Logger: slog.Default(),})if err != nil {@@ -186,6 +187,7 @@ func TestOpencodeV1StillDeliversMCPConfig(t *testing.T) {ExecutablePath: fakePath,CLIVersion: "1.18.31",BuiltinRuntime: true,+ Env: map[string]string{opencodeTransportEnv: "run"},Logger: slog.Default(),})if err != nil {@@ -238,7 +240,7 @@ func TestOpencodeV2ArgvOmitsDirAndFoldsVariant(t *testing.T) {CLIVersion: "opencode v2.0.10",BuiltinRuntime: true,Logger: slog.Default(),- Env: map[string]string{+ Env: map[string]string{opencodeTransportEnv: "run","OPENCODE_ARGS_FILE": argsFile,"OPENCODE_PWD_FILE": pwdFile,},@@ -309,7 +311,7 @@ func TestOpencodeV1ArgvKeepsDirAndVariant(t *testing.T) {CLIVersion: "1.18.31",BuiltinRuntime: true,Logger: slog.Default(),- Env: map[string]string{"OPENCODE_ARGS_FILE": argsFile},+ Env: map[string]string{opencodeTransportEnv: "run", "OPENCODE_ARGS_FILE": argsFile},})if err != nil {t.Fatalf("new opencode backend: %v", err)@@ -567,7 +569,7 @@ func TestOpencodeV2CancelInterruptsThroughRunConnection(t *testing.T) {CLIVersion: "opencode v2.0.10",BuiltinRuntime: true,Logger: slog.Default(),- Env: map[string]string{"MULTICA_TEST_ENV": "task-marker"},+ Env: map[string]string{opencodeTransportEnv: "run", "MULTICA_TEST_ENV": "task-marker"},})if err != nil {t.Fatalf("new opencode backend: %v", err)