oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package fakeopencode is a stand-in for the pinned OpenCode 2.2.7 in its
2// Agent Client Protocol mode (`opencode acp`), reproducing what Equipo
3// relies on as recorded from the real binary
4// (internal/runner/provider/opencode/testdata): initialize with its
5// version; session/new and session/load (which replays the session's
6// history as updates first) with the session's model option; a
7// session/prompt answered at the turn's end with its stop reason and the
8// turn's usage (input uncached, output without reasoning, thought and
9// cached tokens; zero for a figure the provider did not give); text as
10// agent_message_chunk; a tool call announced before its arguments, then
11// in_progress with them, then completed or failed; permissions from the
12// configuration, the last matching rule winning, no match asking
13// (session/request_permission, a rejection ending the turn cancelled);
14// session/cancel; a refused key as error -32000 and a rate limit as
15// -32603 provider.rate-limit; and Equipo's MCP tools (equipo_<tool>)
16// through the configured local server.
17//
18// Like the real one, it reads the configuration from
19// $XDG_CONFIG_HOME/opencode/opencode.json, and also the project's
20// opencode.json (its permissions and instructions) and AGENTS.md unless
21// OPENCODE_DISABLE_PROJECT_CONFIG is set, so a hostile repository
22// reaches a launch that leaves that switch out.
23//
24// Test binaries call Main when they are started as "opencode". Prompt
25// words steer a run, as fakepi's: "[Equipo: engineering]" applies each
26// "edit:<path>|<old>|<new>" and calls submit_candidate; "[Equipo:
27// review]" calls submit_review (approve, or changes_requested for each
28// "review:changes:<path>|<line>|<text>"); "[Equipo: question]" answers
29// with the session's message count; "read:<path>" reads a file;
30// "shell:<command>" runs it with sh until the end of the line;
31// "askshell" asks for a shell call whatever the rules; a workspace holding
32// .fake-opencode-stall makes initialize never answer; "keyrefused",
33// "ratelimited", "nousage" (an ended turn with zero usage), "sleep:<ms>",
34// "costly:<dollars>" (adds to the session's cumulative reported cost),
35// "flood:<n>", "thinking" (reasoning tokens), "echokey" (the key in the
36// reply) and "unknown-event".
37package fakeopencode
38
39import (
40 "bufio"
41 "crypto/rand"
42 "encoding/json"
43 "fmt"
44 "io"
45 "os"
46 "os/exec"
47 "path/filepath"
48 "regexp"
49 "strconv"
50 "strings"
51 "sync"
52 "time"
53)
54
55// Version is the pinned OpenCode the fake stands in for.
56const Version = "2.2.7"
57
58var (
59 editWord = regexp.MustCompile(`edit:([^|\n]+)\|([^|\n]*)\|([^\n]*)`)
60 reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`)
61 readWord = regexp.MustCompile(`read:([^\s"\\]+)`)
62 shellWord = regexp.MustCompile(`shell:([^\n]+)`)
63 sleepWord = regexp.MustCompile(`sleep:([0-9]+)`)
64 floodWord = regexp.MustCompile(`flood:([0-9]+)`)
65 costWord = regexp.MustCompile(`costly:([0-9.]+)`)
66)
67
68type rule struct{ Action, Resource, Effect string }
69
70type config struct {
71 Model string `json:"model"`
72 Providers map[string]struct {
73 Env []string `json:"env"`
74 } `json:"providers"`
75 MCP map[string]struct {
76 Type string `json:"type"`
77 Command []string `json:"command"`
78 } `json:"mcp"`
79 Permissions []rule `json:"permissions"`
80 Instructions []string `json:"instructions"`
81}
82
83type fake struct {
84 outMu sync.Mutex
85 out io.Writer
86 cfg config
87 cwd string
88 db string
89 session string
90 key string
91 context string
92
93 mu sync.Mutex
94 nextID int
95 answers map[string]chan string
96 cancel chan struct{}
97 cancelMu sync.Once
98 running sync.WaitGroup
99
100 mcpIn io.Writer
101 mcpOut *bufio.Reader
102 callID int
103}
104
105// Main runs `opencode acp`.
106func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
107 if len(args) == 1 && (args[0] == "--version" || args[0] == "-v") {
108 fmt.Fprintln(stdout, "opencode v"+Version)
109 return 0
110 }
111 if len(args) != 1 || args[0] != "acp" {
112 fmt.Fprintln(stderr, "fakeopencode: only acp")
113 return 2
114 }
115 f := &fake{out: stdout, answers: map[string]chan string{}}
116 f.cwd, _ = os.Getwd()
117 raw, err := os.ReadFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "opencode", "opencode.json"))
118 if err != nil || json.Unmarshal(raw, &f.cfg) != nil {
119 fmt.Fprintln(stderr, "fakeopencode: no configuration")
120 return 2
121 }
122 f.db = filepath.Join(os.Getenv("XDG_DATA_HOME"), "opencode", "opencode.db")
123 for _, p := range f.cfg.Providers {
124 if len(p.Env) == 1 {
125 f.key = os.Getenv(p.Env[0])
126 }
127 }
128 if os.Getenv("OPENCODE_DISABLE_PROJECT_CONFIG") != "1" {
129 // The project's configuration and instructions, as the real
130 // OpenCode reads them unless the switch is set.
131 var project config
132 if raw, err := os.ReadFile(filepath.Join(f.cwd, "opencode.json")); err == nil && json.Unmarshal(raw, &project) == nil {
133 f.cfg.Permissions = append(f.cfg.Permissions, project.Permissions...)
134 for _, name := range project.Instructions {
135 if raw, err := os.ReadFile(filepath.Join(f.cwd, name)); err == nil {
136 f.context += string(raw)
137 }
138 }
139 }
140 if raw, err := os.ReadFile(filepath.Join(f.cwd, "AGENTS.md")); err == nil {
141 f.context += string(raw)
142 }
143 }
144 s := bufio.NewScanner(stdin)
145 s.Buffer(make([]byte, 0, 64<<10), 16<<20)
146 for s.Scan() {
147 var m struct {
148 ID json.RawMessage `json:"id"`
149 Method string `json:"method"`
150 Params json.RawMessage `json:"params"`
151 Result json.RawMessage `json:"result"`
152 }
153 if json.Unmarshal(s.Bytes(), &m) != nil {
154 continue
155 }
156 switch m.Method {
157 case "initialize":
158 if _, err := os.Stat(filepath.Join(f.cwd, ".fake-opencode-stall")); err == nil {
159 // A start that never answers (a test's workspace asks for it).
160 time.Sleep(time.Hour)
161 }
162 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}})
163 case "session/new":
164 f.session = newID()
165 f.reply(m.ID, map[string]any{"sessionId": f.session, "configOptions": f.options()})
166 case "session/load":
167 var p struct{ SessionID string }
168 json.Unmarshal(m.Params, &p)
169 history := f.history(p.SessionID)
170 if len(history) == 0 {
171 f.fail(m.ID, -32603, "Session not found", "session.not-found")
172 continue
173 }
174 f.session = p.SessionID
175 for _, h := range history {
176 if h.Role == "cost" {
177 continue
178 }
179 kind := "user_message_chunk"
180 if h.Role == "assistant" {
181 kind = "agent_message_chunk"
182 }
183 f.update(map[string]any{"sessionUpdate": kind, "content": map[string]string{"type": "text", "text": h.Text}})
184 }
185 f.reply(m.ID, map[string]any{"configOptions": f.options()})
186 case "session/prompt":
187 var p struct {
188 SessionID string `json:"sessionId"`
189 Prompt []struct{ Text string }
190 }
191 json.Unmarshal(m.Params, &p)
192 text := ""
193 for _, b := range p.Prompt {
194 text += b.Text
195 }
196 f.mu.Lock()
197 f.cancel, f.cancelMu = make(chan struct{}), sync.Once{}
198 f.mu.Unlock()
199 f.running.Add(1)
200 go func(id json.RawMessage) { defer f.running.Done(); f.run(id, text) }(m.ID)
201 case "session/cancel":
202 f.mu.Lock()
203 if f.cancel != nil {
204 c := f.cancel
205 f.cancelMu.Do(func() { close(c) })
206 }
207 f.mu.Unlock()
208 case "":
209 // The client's answer to a permission request.
210 f.mu.Lock()
211 ch := f.answers[string(m.ID)]
212 f.mu.Unlock()
213 if ch != nil {
214 var r struct {
215 Outcome struct{ Outcome, OptionID string } `json:"outcome"`
216 }
217 json.Unmarshal(m.Result, &r)
218 ch <- r.Outcome.OptionID
219 }
220 default:
221 if len(m.ID) > 0 {
222 f.fail(m.ID, -32601, "Method not found", "")
223 }
224 }
225 }
226 f.running.Wait()
227 return 0
228}
229
230func newID() string {
231 const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
232 var b [26]byte
233 rand.Read(b[:])
234 for i := range b {
235 b[i] = alphabet[int(b[i])%len(alphabet)]
236 }
237 return "ses_" + string(b[:])
238}
239
240func (f *fake) send(v any) {
241 raw, _ := json.Marshal(v)
242 f.outMu.Lock()
243 defer f.outMu.Unlock()
244 f.out.Write(append(raw, '\n'))
245}
246
247func (f *fake) reply(id json.RawMessage, result any) {
248 f.send(map[string]any{"jsonrpc": "2.0", "id": id, "result": result})
249}
250
251func (f *fake) fail(id json.RawMessage, code int, message, name string) {
252 data := map[string]any{}
253 if name != "" {
254 data = map[string]any{"service": "session", "errorName": name}
255 }
256 f.send(map[string]any{"jsonrpc": "2.0", "id": id, "error": map[string]any{"code": code, "message": message, "data": data}})
257}
258
259func (f *fake) update(u map[string]any) {
260 f.send(map[string]any{"jsonrpc": "2.0", "method": "session/update", "params": map[string]any{"sessionId": f.session, "update": u}})
261}
262
263func (f *fake) options() []any {
264 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}}}}
265}
266
267type entry struct{ Session, Role, Text string }
268
269func (f *fake) history(id string) []entry {
270 raw, err := os.ReadFile(f.db)
271 if err != nil {
272 return nil
273 }
274 var out []entry
275 for _, line := range strings.Split(string(raw), "\n") {
276 var e entry
277 if json.Unmarshal([]byte(line), &e) == nil && e.Session == id {
278 out = append(out, e)
279 }
280 }
281 return out
282}
283
284func (f *fake) record(role, text string) {
285 os.MkdirAll(filepath.Dir(f.db), 0700)
286 file, err := os.OpenFile(f.db, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
287 if err != nil {
288 return
289 }
290 defer file.Close()
291 raw, _ := json.Marshal(entry{f.session, role, text})
292 file.Write(append(raw, '\n'))
293}
294
295func (f *fake) cancelled() bool {
296 f.mu.Lock()
297 c := f.cancel
298 f.mu.Unlock()
299 select {
300 case <-c:
301 return true
302 default:
303 return false
304 }
305}
306
307// effect is the configuration's rule for action on resource: the last
308// matching rule wins, no match asks; a path outside the working
309// directory is also an external_directory.
310func (f *fake) effect(action, path string) string {
311 match := func(a string) string {
312 out := "ask"
313 for _, r := range f.cfg.Permissions {
314 if r.Action == a || r.Action == "*" {
315 out = r.Effect
316 }
317 }
318 return out
319 }
320 e := match(action)
321 if path != "" && e != "deny" {
322 p := path
323 if !filepath.IsAbs(p) {
324 p = filepath.Join(f.cwd, p)
325 }
326 if real, err := filepath.EvalSymlinks(p); err == nil {
327 p = real
328 }
329 if p != f.cwd && !strings.HasPrefix(p, f.cwd+"/") {
330 if x := match("external_directory"); x != "allow" {
331 return x
332 }
333 }
334 }
335 return e
336}
337
338type turn struct {
339 steps, thought int64
340 notes []string
341 calls int
342 rejected bool
343}
344
345// ask is a permission request; true when the client allowed it.
346func (f *fake) ask(callID, name string, args map[string]any) bool {
347 f.mu.Lock()
348 n := f.nextID
349 f.nextID++
350 id := fmt.Sprintf("%d", n)
351 ch := make(chan string, 1)
352 f.answers[id] = ch
353 c := f.cancel
354 f.mu.Unlock()
355 f.send(map[string]any{"jsonrpc": "2.0", "id": n, "method": "session/request_permission", "params": map[string]any{"sessionId": f.session,
356 "toolCall": map[string]any{"toolCallId": callID, "name": name, "title": name, "kind": "execute", "status": "pending", "rawInput": args},
357 "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"}}}})
358 select {
359 case o := <-ch:
360 return o == "once" || o == "always"
361 case <-c:
362 return false
363 }
364}
365
366// tool plays one model request that calls name, and the call.
367func (f *fake) tool(t *turn, name string, args map[string]any, path string, force bool) (string, bool) {
368 t.steps++
369 t.calls++
370 id := fmt.Sprintf("call_%d_%d", time.Now().UnixNano(), t.calls)
371 f.update(map[string]any{"sessionUpdate": "tool_call", "toolCallId": id, "name": name, "title": name, "kind": "other", "status": "pending", "locations": []any{}, "rawInput": map[string]any{}})
372 // As recorded: in progress with its arguments, then the permission.
373 f.update(map[string]any{"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "in_progress", "rawInput": args})
374 action := name
375 e := f.effect(action, path)
376 if force {
377 e = "ask"
378 }
379 switch e {
380 case "deny":
381 msg := "Permission denied: " + action
382 if path != "" && f.effect(action, "") != "deny" {
383 msg = "Permission denied: external_directory"
384 }
385 f.update(map[string]any{"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "failed", "rawInput": args, "rawOutput": map[string]any{"error": msg}})
386 return msg, true
387 case "ask":
388 if !f.ask(id, name, args) {
389 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"}})
390 t.rejected = true
391 return "declined", true
392 }
393 }
394 text, isError := f.execute(name, args)
395 status := "completed"
396 if isError {
397 status = "failed"
398 }
399 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}}}})
400 return text, isError
401}
402
403func (f *fake) execute(name string, args map[string]any) (string, bool) {
404 if tool, ok := strings.CutPrefix(name, "equipo_"); ok {
405 return f.callTool(tool, args)
406 }
407 switch name {
408 case "read":
409 p, _ := args["path"].(string)
410 raw, err := os.ReadFile(p)
411 if err != nil {
412 return err.Error(), true
413 }
414 return string(raw), false
415 case "edit":
416 p, _ := args["path"].(string)
417 old, _ := args["oldString"].(string)
418 repl, _ := args["newString"].(string)
419 raw, err := os.ReadFile(p)
420 if err != nil {
421 return err.Error(), true
422 }
423 if err := os.WriteFile(p, []byte(strings.Replace(string(raw), old, repl, 1)), 0644); err != nil {
424 return err.Error(), true
425 }
426 return "Edited.", false
427 case "shell":
428 cmd, _ := args["command"].(string)
429 out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
430 if err != nil {
431 return string(out) + err.Error(), true
432 }
433 return string(out), false
434 }
435 return "unknown tool", true
436}
437
438// run plays one prompt to its answer.
439func (f *fake) run(id json.RawMessage, prompt string) {
440 f.record("user", prompt)
441 t := &turn{steps: 1}
442 usage := func() map[string]any {
443 u := map[string]any{"inputTokens": 60 * t.steps, "outputTokens": 7 * t.steps, "totalTokens": 107*t.steps + t.thought, "cachedReadTokens": 40 * t.steps}
444 if t.thought > 0 {
445 u["thoughtTokens"] = t.thought
446 }
447 return u
448 }
449 end := func(stop string) {
450 // The session's cost so far, as OpenCode reports it: cumulative.
451 if m := costWord.FindStringSubmatch(prompt); m != nil {
452 f.record("cost", m[1])
453 }
454 total := 0.0
455 for _, h := range f.history(f.session) {
456 if h.Role == "cost" {
457 v, _ := strconv.ParseFloat(h.Text, 64)
458 total += v
459 }
460 }
461 f.update(map[string]any{"sessionUpdate": "usage_update", "used": 107, "size": 200000, "cost": map[string]any{"amount": total, "currency": "USD"}})
462 f.reply(id, map[string]any{"stopReason": stop, "usage": usage(), "_meta": map[string]any{}})
463 }
464 switch {
465 case strings.Contains(prompt, "keyrefused") || f.key == "":
466 f.fail(id, -32000, "Authentication required: provider authentication required", "")
467 return
468 case strings.Contains(prompt, "ratelimited"):
469 for i := 2; i <= 3; i++ {
470 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}}}})
471 }
472 f.fail(id, -32603, "Internal error: limit", "provider.rate-limit")
473 return
474 case strings.Contains(prompt, "nousage"):
475 f.update(map[string]any{"sessionUpdate": "agent_message_chunk", "content": map[string]string{"type": "text", "text": "ok"}})
476 f.reply(id, map[string]any{"stopReason": "end_turn", "usage": map[string]any{"inputTokens": 0, "outputTokens": 0, "totalTokens": 0}, "_meta": map[string]any{}})
477 return
478 }
479 if strings.Contains(prompt, "thinking") {
480 t.thought = 5
481 }
482 if strings.Contains(prompt, "unknown-event") {
483 f.update(map[string]any{"sessionUpdate": "fake_unknown_update", "detail": "not for Equipo"})
484 }
485 if strings.Contains(prompt, "askshell") {
486 f.tool(t, "shell", map[string]any{"command": "true"}, "", true)
487 if t.rejected {
488 end("cancelled")
489 return
490 }
491 }
492 for _, m := range readWord.FindAllStringSubmatch(prompt, -1) {
493 text, isError := f.tool(t, "read", map[string]any{"path": m[1]}, m[1], false)
494 if t.rejected {
495 end("cancelled")
496 return
497 }
498 if isError {
499 t.notes = append(t.notes, "[read "+m[1]+" refused: "+text+"]")
500 } else {
501 t.notes = append(t.notes, "[read "+m[1]+": "+strings.TrimSpace(text)+"]")
502 }
503 }
504 for _, m := range shellWord.FindAllStringSubmatch(prompt, -1) {
505 text, isError := f.tool(t, "shell", map[string]any{"command": strings.TrimSpace(m[1])}, "", false)
506 if t.rejected {
507 end("cancelled")
508 return
509 }
510 t.notes = append(t.notes, fmt.Sprintf("[shell %v: %s]", !isError, strings.TrimSpace(text)))
511 }
512 reply := "ok"
513 switch {
514 case strings.HasPrefix(prompt, "[Equipo: engineering]"):
515 for _, m := range editWord.FindAllStringSubmatch(prompt, -1) {
516 if _, isError := f.tool(t, "edit", map[string]any{"path": m[1], "oldString": m[2], "newString": m[3]}, m[1], false); !isError {
517 t.notes = append(t.notes, fmt.Sprintf("Replaced %q with %q in %s.", m[2], m[3], m[1]))
518 }
519 }
520 if text, isError := f.tool(t, "equipo_submit_candidate", map[string]any{}, "", false); isError {
521 t.notes = append(t.notes, "[submit_candidate failed: "+text+"]")
522 }
523 reply = "Headline: Made the change the task asks for.\n\n" + strings.Join(t.notes, " ")
524 case strings.HasPrefix(prompt, "[Equipo: review]"):
525 verdict, headline, summary, findings := "approve", "Approved.", "The change does what the task asks.", []map[string]any{}
526 for _, m := range reviewChanges.FindAllStringSubmatch(prompt, -1) {
527 line, _ := strconv.Atoi(m[2])
528 verdict, headline, summary = "changes_requested", "Asked for one more change.", "One thing needs changing."
529 findings = append(findings, map[string]any{"path": m[1], "line": line, "text": m[3]})
530 }
531 reply = summary + " (from OpenCode)" + strings.Join(t.notes, " ")
532 if text, isError := f.tool(t, "equipo_submit_review", map[string]any{"verdict": verdict, "headline": headline, "summary": summary + " (from OpenCode)", "findings": findings}, "", false); isError {
533 reply += " [submit_review failed: " + text + "]"
534 }
535 case strings.HasPrefix(prompt, "[Equipo: question]"):
536 n := 0
537 for _, h := range f.history(f.session) {
538 if h.Role != "cost" {
539 n++
540 }
541 }
542 reply = fmt.Sprintf("Answered from my session (message %d).", n) + strings.Join(t.notes, " ")
543 default:
544 reply = "ok " + strings.Join(t.notes, " ")
545 }
546 if f.context != "" {
547 reply += " [context: " + strings.TrimSpace(f.context) + "]"
548 }
549 if strings.Contains(prompt, "echokey") {
550 reply = "the key is " + f.key + " and that is all"
551 if strings.HasPrefix(prompt, "[Equipo: review]") {
552 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)
553 }
554 }
555 if m := floodWord.FindStringSubmatch(prompt); m != nil {
556 n, _ := strconv.Atoi(m[1])
557 reply = strings.Repeat("f", n)
558 }
559 half := len(reply) / 2
560 f.update(map[string]any{"sessionUpdate": "agent_message_chunk", "content": map[string]string{"type": "text", "text": reply[:half]}})
561 if m := sleepWord.FindStringSubmatch(prompt); m != nil {
562 ms, _ := strconv.Atoi(m[1])
563 f.mu.Lock()
564 c := f.cancel
565 f.mu.Unlock()
566 select {
567 case <-time.After(time.Duration(ms) * time.Millisecond):
568 case <-c:
569 }
570 }
571 if f.cancelled() {
572 // Cancelled mid-request: the request's usage never came.
573 f.reply(id, map[string]any{"stopReason": "cancelled", "_meta": map[string]any{}})
574 return
575 }
576 f.update(map[string]any{"sessionUpdate": "agent_message_chunk", "content": map[string]string{"type": "text", "text": reply[half:]}})
577 f.record("assistant", reply)
578 end("end_turn")
579}
580
581func (f *fake) callTool(name string, input map[string]any) (string, bool) {
582 if f.mcpIn == nil {
583 if msg := f.connectMCP(); msg != "" {
584 return msg, true
585 }
586 }
587 f.callID++
588 raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + f.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input}})
589 if _, err := f.mcpIn.Write(append(raw, '\n')); err != nil {
590 return "MCP write failed", true
591 }
592 line, err := f.mcpOut.ReadBytes('\n')
593 var reply struct {
594 Result struct {
595 Content []struct {
596 Text string `json:"text"`
597 } `json:"content"`
598 IsError bool `json:"isError"`
599 } `json:"result"`
600 Error *struct{} `json:"error"`
601 }
602 if err != nil || json.Unmarshal(line, &reply) != nil || reply.Error != nil || len(reply.Result.Content) == 0 {
603 return "MCP call failed", true
604 }
605 return reply.Result.Content[0].Text, reply.Result.IsError
606}
607
608// connectMCP starts the equipo server the configuration names.
609func (f *fake) connectMCP() string {
610 eq, ok := f.cfg.MCP["equipo"]
611 if !ok || eq.Type != "local" || len(eq.Command) == 0 {
612 return "no MCP server configured"
613 }
614 cmd := exec.Command(eq.Command[0], eq.Command[1:]...)
615 in, _ := cmd.StdinPipe()
616 out, _ := cmd.StdoutPipe()
617 if cmd.Start() != nil {
618 return "MCP server did not start"
619 }
620 r := bufio.NewReader(out)
621 call := func(id int, method string, params any) json.RawMessage {
622 raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})
623 if _, err := in.Write(append(raw, '\n')); err != nil {
624 return nil
625 }
626 line, err := r.ReadBytes('\n')
627 var reply struct {
628 Result json.RawMessage `json:"result"`
629 }
630 if err != nil || json.Unmarshal(line, &reply) != nil {
631 return nil
632 }
633 return reply.Result
634 }
635 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 {
636 return "MCP initialize failed"
637 }
638 note, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"})
639 in.Write(append(note, '\n'))
640 if call(2, "tools/list", map[string]any{}) == nil {
641 return "MCP tools/list failed"
642 }
643 f.mcpIn, f.mcpOut = in, r
644 return ""
645}
646