// Package fakeopencode is a stand-in for the pinned OpenCode 2.2.7 in its // Agent Client Protocol mode (`opencode acp`), reproducing what Equipo // relies on as recorded from the real binary // (internal/runner/provider/opencode/testdata): initialize with its // version; session/new and session/load (which replays the session's // history as updates first) with the session's model option; a // session/prompt answered at the turn's end with its stop reason and the // turn's usage (input uncached, output without reasoning, thought and // cached tokens; zero for a figure the provider did not give); text as // agent_message_chunk; a tool call announced before its arguments, then // in_progress with them, then completed or failed; permissions from the // configuration, the last matching rule winning, no match asking // (session/request_permission, a rejection ending the turn cancelled); // session/cancel; a refused key as error -32000 and a rate limit as // -32603 provider.rate-limit; and Equipo's MCP tools (equipo_) // through the configured local server. // // Like the real one, it reads the configuration from // $XDG_CONFIG_HOME/opencode/opencode.json, and also the project's // opencode.json (its permissions and instructions) and AGENTS.md unless // OPENCODE_DISABLE_PROJECT_CONFIG is set, so a hostile repository // reaches a launch that leaves that switch out. // // Test binaries call Main when they are started as "opencode". Prompt // words steer a run, as fakepi's: "[Equipo: engineering]" applies each // "edit:||" and calls submit_candidate; "[Equipo: // review]" calls submit_review (approve, or changes_requested for each // "review:changes:||"); "[Equipo: question]" answers // with the session's message count; "read:" reads a file; // "shell:" runs it with sh until the end of the line; // "askshell" asks for a shell call whatever the rules; a workspace holding // .fake-opencode-stall makes initialize never answer; "keyrefused", // "ratelimited", "nousage" (an ended turn with zero usage), "sleep:", // "costly:" (adds to the session's cumulative reported cost), // "flood:", "thinking" (reasoning tokens), "echokey" (the key in the // reply) and "unknown-event". package fakeopencode import ( "bufio" "crypto/rand" "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "sync" "time" ) // Version is the pinned OpenCode the fake stands in for. const Version = "2.2.7" var ( editWord = regexp.MustCompile(`edit:([^|\n]+)\|([^|\n]*)\|([^\n]*)`) reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`) readWord = regexp.MustCompile(`read:([^\s"\\]+)`) shellWord = regexp.MustCompile(`shell:([^\n]+)`) sleepWord = regexp.MustCompile(`sleep:([0-9]+)`) floodWord = regexp.MustCompile(`flood:([0-9]+)`) costWord = regexp.MustCompile(`costly:([0-9.]+)`) ) type rule struct{ Action, Resource, Effect string } type config struct { Model string `json:"model"` Providers map[string]struct { Env []string `json:"env"` } `json:"providers"` MCP map[string]struct { Type string `json:"type"` Command []string `json:"command"` } `json:"mcp"` Permissions []rule `json:"permissions"` Instructions []string `json:"instructions"` } type fake struct { outMu sync.Mutex out io.Writer cfg config cwd string db string session string key string context string mu sync.Mutex nextID int answers map[string]chan string cancel chan struct{} cancelMu sync.Once running sync.WaitGroup mcpIn io.Writer mcpOut *bufio.Reader callID int } // Main runs `opencode acp`. func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { if len(args) == 1 && (args[0] == "--version" || args[0] == "-v") { fmt.Fprintln(stdout, "opencode v"+Version) return 0 } if len(args) != 1 || args[0] != "acp" { fmt.Fprintln(stderr, "fakeopencode: only acp") return 2 } f := &fake{out: stdout, answers: map[string]chan string{}} f.cwd, _ = os.Getwd() raw, err := os.ReadFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "opencode", "opencode.json")) if err != nil || json.Unmarshal(raw, &f.cfg) != nil { fmt.Fprintln(stderr, "fakeopencode: no configuration") return 2 } f.db = filepath.Join(os.Getenv("XDG_DATA_HOME"), "opencode", "opencode.db") for _, p := range f.cfg.Providers { if len(p.Env) == 1 { f.key = os.Getenv(p.Env[0]) } } if os.Getenv("OPENCODE_DISABLE_PROJECT_CONFIG") != "1" { // The project's configuration and instructions, as the real // OpenCode reads them unless the switch is set. var project config if raw, err := os.ReadFile(filepath.Join(f.cwd, "opencode.json")); err == nil && json.Unmarshal(raw, &project) == nil { f.cfg.Permissions = append(f.cfg.Permissions, project.Permissions...) for _, name := range project.Instructions { if raw, err := os.ReadFile(filepath.Join(f.cwd, name)); err == nil { f.context += string(raw) } } } if raw, err := os.ReadFile(filepath.Join(f.cwd, "AGENTS.md")); err == nil { f.context += string(raw) } } s := bufio.NewScanner(stdin) s.Buffer(make([]byte, 0, 64<<10), 16<<20) for s.Scan() { var m struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` Result json.RawMessage `json:"result"` } if json.Unmarshal(s.Bytes(), &m) != nil { continue } switch m.Method { case "initialize": if _, err := os.Stat(filepath.Join(f.cwd, ".fake-opencode-stall")); err == nil { // A start that never answers (a test's workspace asks for it). time.Sleep(time.Hour) } f.reply(m.ID, map[string]any{"protocolVersion": 1, "agentCapabilities": map[string]any{"loadSession": true}, "authMethods": []any{}, "agentInfo": map[string]string{"name": "OpenCode", "version": Version}}) case "session/new": f.session = newID() f.reply(m.ID, map[string]any{"sessionId": f.session, "configOptions": f.options()}) case "session/load": var p struct{ SessionID string } json.Unmarshal(m.Params, &p) history := f.history(p.SessionID) if len(history) == 0 { f.fail(m.ID, -32603, "Session not found", "session.not-found") continue } f.session = p.SessionID for _, h := range history { if h.Role == "cost" { continue } kind := "user_message_chunk" if h.Role == "assistant" { kind = "agent_message_chunk" } f.update(map[string]any{"sessionUpdate": kind, "content": map[string]string{"type": "text", "text": h.Text}}) } f.reply(m.ID, map[string]any{"configOptions": f.options()}) case "session/prompt": var p struct { SessionID string `json:"sessionId"` Prompt []struct{ Text string } } json.Unmarshal(m.Params, &p) text := "" for _, b := range p.Prompt { text += b.Text } f.mu.Lock() f.cancel, f.cancelMu = make(chan struct{}), sync.Once{} f.mu.Unlock() f.running.Add(1) go func(id json.RawMessage) { defer f.running.Done(); f.run(id, text) }(m.ID) case "session/cancel": f.mu.Lock() if f.cancel != nil { c := f.cancel f.cancelMu.Do(func() { close(c) }) } f.mu.Unlock() case "": // The client's answer to a permission request. f.mu.Lock() ch := f.answers[string(m.ID)] f.mu.Unlock() if ch != nil { var r struct { Outcome struct{ Outcome, OptionID string } `json:"outcome"` } json.Unmarshal(m.Result, &r) ch <- r.Outcome.OptionID } default: if len(m.ID) > 0 { f.fail(m.ID, -32601, "Method not found", "") } } } f.running.Wait() return 0 } func newID() string { const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var b [26]byte rand.Read(b[:]) for i := range b { b[i] = alphabet[int(b[i])%len(alphabet)] } return "ses_" + string(b[:]) } func (f *fake) send(v any) { raw, _ := json.Marshal(v) f.outMu.Lock() defer f.outMu.Unlock() f.out.Write(append(raw, '\n')) } func (f *fake) reply(id json.RawMessage, result any) { f.send(map[string]any{"jsonrpc": "2.0", "id": id, "result": result}) } func (f *fake) fail(id json.RawMessage, code int, message, name string) { data := map[string]any{} if name != "" { data = map[string]any{"service": "session", "errorName": name} } f.send(map[string]any{"jsonrpc": "2.0", "id": id, "error": map[string]any{"code": code, "message": message, "data": data}}) } func (f *fake) update(u map[string]any) { f.send(map[string]any{"jsonrpc": "2.0", "method": "session/update", "params": map[string]any{"sessionId": f.session, "update": u}}) } func (f *fake) options() []any { return []any{map[string]any{"id": "model", "name": "Model", "category": "model", "type": "select", "currentValue": f.cfg.Model, "options": []any{map[string]string{"value": f.cfg.Model, "name": f.cfg.Model}}}} } type entry struct{ Session, Role, Text string } func (f *fake) history(id string) []entry { raw, err := os.ReadFile(f.db) if err != nil { return nil } var out []entry for _, line := range strings.Split(string(raw), "\n") { var e entry if json.Unmarshal([]byte(line), &e) == nil && e.Session == id { out = append(out, e) } } return out } func (f *fake) record(role, text string) { os.MkdirAll(filepath.Dir(f.db), 0700) file, err := os.OpenFile(f.db, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) if err != nil { return } defer file.Close() raw, _ := json.Marshal(entry{f.session, role, text}) file.Write(append(raw, '\n')) } func (f *fake) cancelled() bool { f.mu.Lock() c := f.cancel f.mu.Unlock() select { case <-c: return true default: return false } } // effect is the configuration's rule for action on resource: the last // matching rule wins, no match asks; a path outside the working // directory is also an external_directory. func (f *fake) effect(action, path string) string { match := func(a string) string { out := "ask" for _, r := range f.cfg.Permissions { if r.Action == a || r.Action == "*" { out = r.Effect } } return out } e := match(action) if path != "" && e != "deny" { p := path if !filepath.IsAbs(p) { p = filepath.Join(f.cwd, p) } if real, err := filepath.EvalSymlinks(p); err == nil { p = real } if p != f.cwd && !strings.HasPrefix(p, f.cwd+"/") { if x := match("external_directory"); x != "allow" { return x } } } return e } type turn struct { steps, thought int64 notes []string calls int rejected bool } // ask is a permission request; true when the client allowed it. func (f *fake) ask(callID, name string, args map[string]any) bool { f.mu.Lock() n := f.nextID f.nextID++ id := fmt.Sprintf("%d", n) ch := make(chan string, 1) f.answers[id] = ch c := f.cancel f.mu.Unlock() f.send(map[string]any{"jsonrpc": "2.0", "id": n, "method": "session/request_permission", "params": map[string]any{"sessionId": f.session, "toolCall": map[string]any{"toolCallId": callID, "name": name, "title": name, "kind": "execute", "status": "pending", "rawInput": args}, "options": []any{map[string]string{"optionId": "once", "kind": "allow_once", "name": "Allow once"}, map[string]string{"optionId": "always", "kind": "allow_always", "name": "Always allow"}, map[string]string{"optionId": "reject", "kind": "reject_once", "name": "Reject"}}}}) select { case o := <-ch: return o == "once" || o == "always" case <-c: return false } } // tool plays one model request that calls name, and the call. func (f *fake) tool(t *turn, name string, args map[string]any, path string, force bool) (string, bool) { t.steps++ t.calls++ id := fmt.Sprintf("call_%d_%d", time.Now().UnixNano(), t.calls) f.update(map[string]any{"sessionUpdate": "tool_call", "toolCallId": id, "name": name, "title": name, "kind": "other", "status": "pending", "locations": []any{}, "rawInput": map[string]any{}}) // As recorded: in progress with its arguments, then the permission. f.update(map[string]any{"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "in_progress", "rawInput": args}) action := name e := f.effect(action, path) if force { e = "ask" } switch e { case "deny": msg := "Permission denied: " + action if path != "" && f.effect(action, "") != "deny" { msg = "Permission denied: external_directory" } f.update(map[string]any{"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "failed", "rawInput": args, "rawOutput": map[string]any{"error": msg}}) return msg, true case "ask": if !f.ask(id, name, args) { f.update(map[string]any{"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "failed", "rawInput": args, "rawOutput": map[string]any{"error": "The user declined this tool call"}}) t.rejected = true return "declined", true } } text, isError := f.execute(name, args) status := "completed" if isError { status = "failed" } f.update(map[string]any{"sessionUpdate": "tool_call_update", "toolCallId": id, "status": status, "rawInput": args, "content": []any{map[string]any{"type": "content", "content": map[string]string{"type": "text", "text": text}}}}) return text, isError } func (f *fake) execute(name string, args map[string]any) (string, bool) { if tool, ok := strings.CutPrefix(name, "equipo_"); ok { return f.callTool(tool, args) } switch name { case "read": p, _ := args["path"].(string) raw, err := os.ReadFile(p) if err != nil { return err.Error(), true } return string(raw), false case "edit": p, _ := args["path"].(string) old, _ := args["oldString"].(string) repl, _ := args["newString"].(string) raw, err := os.ReadFile(p) if err != nil { return err.Error(), true } if err := os.WriteFile(p, []byte(strings.Replace(string(raw), old, repl, 1)), 0644); err != nil { return err.Error(), true } return "Edited.", false case "shell": cmd, _ := args["command"].(string) out, err := exec.Command("sh", "-c", cmd).CombinedOutput() if err != nil { return string(out) + err.Error(), true } return string(out), false } return "unknown tool", true } // run plays one prompt to its answer. func (f *fake) run(id json.RawMessage, prompt string) { f.record("user", prompt) t := &turn{steps: 1} usage := func() map[string]any { u := map[string]any{"inputTokens": 60 * t.steps, "outputTokens": 7 * t.steps, "totalTokens": 107*t.steps + t.thought, "cachedReadTokens": 40 * t.steps} if t.thought > 0 { u["thoughtTokens"] = t.thought } return u } end := func(stop string) { // The session's cost so far, as OpenCode reports it: cumulative. if m := costWord.FindStringSubmatch(prompt); m != nil { f.record("cost", m[1]) } total := 0.0 for _, h := range f.history(f.session) { if h.Role == "cost" { v, _ := strconv.ParseFloat(h.Text, 64) total += v } } f.update(map[string]any{"sessionUpdate": "usage_update", "used": 107, "size": 200000, "cost": map[string]any{"amount": total, "currency": "USD"}}) f.reply(id, map[string]any{"stopReason": stop, "usage": usage(), "_meta": map[string]any{}}) } switch { case strings.Contains(prompt, "keyrefused") || f.key == "": f.fail(id, -32000, "Authentication required: provider authentication required", "") return case strings.Contains(prompt, "ratelimited"): for i := 2; i <= 3; i++ { f.update(map[string]any{"sessionUpdate": "session_info_update", "_meta": map[string]any{"opencode/retry": map[string]any{"attempt": i, "error": map[string]any{"type": "provider.rate-limit", "message": "limit", "status": 429}}}}) } f.fail(id, -32603, "Internal error: limit", "provider.rate-limit") return case strings.Contains(prompt, "nousage"): f.update(map[string]any{"sessionUpdate": "agent_message_chunk", "content": map[string]string{"type": "text", "text": "ok"}}) f.reply(id, map[string]any{"stopReason": "end_turn", "usage": map[string]any{"inputTokens": 0, "outputTokens": 0, "totalTokens": 0}, "_meta": map[string]any{}}) return } if strings.Contains(prompt, "thinking") { t.thought = 5 } if strings.Contains(prompt, "unknown-event") { f.update(map[string]any{"sessionUpdate": "fake_unknown_update", "detail": "not for Equipo"}) } if strings.Contains(prompt, "askshell") { f.tool(t, "shell", map[string]any{"command": "true"}, "", true) if t.rejected { end("cancelled") return } } for _, m := range readWord.FindAllStringSubmatch(prompt, -1) { text, isError := f.tool(t, "read", map[string]any{"path": m[1]}, m[1], false) if t.rejected { end("cancelled") return } if isError { t.notes = append(t.notes, "[read "+m[1]+" refused: "+text+"]") } else { t.notes = append(t.notes, "[read "+m[1]+": "+strings.TrimSpace(text)+"]") } } for _, m := range shellWord.FindAllStringSubmatch(prompt, -1) { text, isError := f.tool(t, "shell", map[string]any{"command": strings.TrimSpace(m[1])}, "", false) if t.rejected { end("cancelled") return } t.notes = append(t.notes, fmt.Sprintf("[shell %v: %s]", !isError, strings.TrimSpace(text))) } reply := "ok" switch { case strings.HasPrefix(prompt, "[Equipo: engineering]"): for _, m := range editWord.FindAllStringSubmatch(prompt, -1) { if _, isError := f.tool(t, "edit", map[string]any{"path": m[1], "oldString": m[2], "newString": m[3]}, m[1], false); !isError { t.notes = append(t.notes, fmt.Sprintf("Replaced %q with %q in %s.", m[2], m[3], m[1])) } } if text, isError := f.tool(t, "equipo_submit_candidate", map[string]any{}, "", false); isError { t.notes = append(t.notes, "[submit_candidate failed: "+text+"]") } reply = "Headline: Made the change the task asks for.\n\n" + strings.Join(t.notes, " ") case strings.HasPrefix(prompt, "[Equipo: review]"): verdict, headline, summary, findings := "approve", "Approved.", "The change does what the task asks.", []map[string]any{} for _, m := range reviewChanges.FindAllStringSubmatch(prompt, -1) { line, _ := strconv.Atoi(m[2]) verdict, headline, summary = "changes_requested", "Asked for one more change.", "One thing needs changing." findings = append(findings, map[string]any{"path": m[1], "line": line, "text": m[3]}) } reply = summary + " (from OpenCode)" + strings.Join(t.notes, " ") if text, isError := f.tool(t, "equipo_submit_review", map[string]any{"verdict": verdict, "headline": headline, "summary": summary + " (from OpenCode)", "findings": findings}, "", false); isError { reply += " [submit_review failed: " + text + "]" } case strings.HasPrefix(prompt, "[Equipo: question]"): n := 0 for _, h := range f.history(f.session) { if h.Role != "cost" { n++ } } reply = fmt.Sprintf("Answered from my session (message %d).", n) + strings.Join(t.notes, " ") default: reply = "ok " + strings.Join(t.notes, " ") } if f.context != "" { reply += " [context: " + strings.TrimSpace(f.context) + "]" } if strings.Contains(prompt, "echokey") { reply = "the key is " + f.key + " and that is all" if strings.HasPrefix(prompt, "[Equipo: review]") { f.tool(t, "equipo_submit_review", map[string]any{"verdict": "approve", "headline": "Key " + f.key, "summary": "I read " + f.key, "findings": []map[string]any{}}, "", false) } } if m := floodWord.FindStringSubmatch(prompt); m != nil { n, _ := strconv.Atoi(m[1]) reply = strings.Repeat("f", n) } half := len(reply) / 2 f.update(map[string]any{"sessionUpdate": "agent_message_chunk", "content": map[string]string{"type": "text", "text": reply[:half]}}) if m := sleepWord.FindStringSubmatch(prompt); m != nil { ms, _ := strconv.Atoi(m[1]) f.mu.Lock() c := f.cancel f.mu.Unlock() select { case <-time.After(time.Duration(ms) * time.Millisecond): case <-c: } } if f.cancelled() { // Cancelled mid-request: the request's usage never came. f.reply(id, map[string]any{"stopReason": "cancelled", "_meta": map[string]any{}}) return } f.update(map[string]any{"sessionUpdate": "agent_message_chunk", "content": map[string]string{"type": "text", "text": reply[half:]}}) f.record("assistant", reply) end("end_turn") } func (f *fake) callTool(name string, input map[string]any) (string, bool) { if f.mcpIn == nil { if msg := f.connectMCP(); msg != "" { return msg, true } } f.callID++ raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + f.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input}}) if _, err := f.mcpIn.Write(append(raw, '\n')); err != nil { return "MCP write failed", true } line, err := f.mcpOut.ReadBytes('\n') var reply struct { Result struct { Content []struct { Text string `json:"text"` } `json:"content"` IsError bool `json:"isError"` } `json:"result"` Error *struct{} `json:"error"` } if err != nil || json.Unmarshal(line, &reply) != nil || reply.Error != nil || len(reply.Result.Content) == 0 { return "MCP call failed", true } return reply.Result.Content[0].Text, reply.Result.IsError } // connectMCP starts the equipo server the configuration names. func (f *fake) connectMCP() string { eq, ok := f.cfg.MCP["equipo"] if !ok || eq.Type != "local" || len(eq.Command) == 0 { return "no MCP server configured" } cmd := exec.Command(eq.Command[0], eq.Command[1:]...) in, _ := cmd.StdinPipe() out, _ := cmd.StdoutPipe() if cmd.Start() != nil { return "MCP server did not start" } r := bufio.NewReader(out) call := func(id int, method string, params any) json.RawMessage { raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) if _, err := in.Write(append(raw, '\n')); err != nil { return nil } line, err := r.ReadBytes('\n') var reply struct { Result json.RawMessage `json:"result"` } if err != nil || json.Unmarshal(line, &reply) != nil { return nil } return reply.Result } if call(1, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]string{"name": "fake-opencode", "version": Version}}) == nil { return "MCP initialize failed" } note, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"}) in.Write(append(note, '\n')) if call(2, "tools/list", map[string]any{}) == nil { return "MCP tools/list failed" } f.mcpIn, f.mcpOut = in, r return "" }