oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "bufio"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "net"
9 "os"
10 "path/filepath"
11 "slices"
12 "strings"
13 "sync"
14
15 "amadan.net/oficina/equipo/internal/runner/provider"
16 "amadan.net/oficina/equipo/internal/runner/provider/claude"
17 "amadan.net/oficina/equipo/internal/wire"
18
19 "amadan.net/oficina/equipo/internal/runner"
20)
21
22const maxToolFrame = 64 << 10
23
24// ToolFunc runs one coordinator tool. useID is the provider's tool-use id
25// when the client sends one. The text goes back to the model.
26type ToolFunc func(ctx context.Context, name, useID string, args json.RawMessage) (text string, isError bool)
27
28// ToolReplyFunc runs one tool whose answer may carry an image too.
29type ToolReplyFunc func(ctx context.Context, name, useID string, args json.RawMessage) toolReply
30
31// toolReply is a tool's answer: its text and, for read_attachment on an
32// image, the image beside it (an MCP image content block).
33type toolReply struct {
34 Text string
35 IsError bool
36 Image *toolImage
37}
38
39// toolImage is an image a tool returns, scaled for the model.
40type toolImage struct {
41 MediaType string
42 Data []byte
43}
44
45// textOnly is a ToolFunc as a ToolReplyFunc.
46func textOnly(call ToolFunc) ToolReplyFunc {
47 if call == nil {
48 return nil
49 }
50 return func(ctx context.Context, name, useID string, args json.RawMessage) toolReply {
51 text, isError := call(ctx, name, useID, args)
52 return toolReply{Text: text, IsError: isError}
53 }
54}
55
56// toolSocket is the runner end of /tool/equipo.sock for one coordinator
57// process. It lists exactly the conversation's tools and Claude's
58// permission callback, which allows only those tools.
59type toolSocket struct {
60 set toolSet
61 call ToolReplyFunc
62 Path string
63 dir string
64 listener *net.UnixListener
65 cancel context.CancelFunc
66 wg sync.WaitGroup
67 peerUID func(fd int) (uint32, error)
68}
69
70// toolPeerUID reads a tool socket peer's user: SO_PEERCRED on Linux,
71// LOCAL_PEERCRED on a Mac (runner peer_*.go). Tests stand in.
72var toolPeerUID = runner.PeerUID
73
74// openToolSocket creates <root>/coord-tool-*/equipo.sock, 0700 and 0600
75// (on a Mac <root>/<random>/s, toolsocket_layout.go). root must be a
76// private directory the model cannot read (toolRoot).
77func openToolSocket(ctx context.Context, root string, call ToolFunc) (*toolSocket, error) {
78 return openToolSet(ctx, root, converseSet(call != nil), call)
79}
80
81// toolSet is what one process's tool socket serves: the tools it lists
82// beside the permission callback, the names it may call, and the
83// callback's answer (nil: no permission tool, as for Codex, which asks
84// through the app-server instead).
85type toolSet struct {
86 current func() toolSet
87 list []any
88 names []string
89 permission func(json.RawMessage) string
90}
91
92// converseSet is the coordinator's: its tools when it has any, and a
93// callback that allows only those.
94func converseSet(tools bool) toolSet {
95 var names []string
96 s := toolSet{}
97 if tools {
98 names = provider.ConverseTools()
99 s.list, s.names = converseTools, names
100 }
101 s.permission = func(raw json.RawMessage) string { return permissionText(raw, names) }
102 return s
103}
104
105func openToolSet(ctx context.Context, root string, set toolSet, call ToolFunc) (*toolSocket, error) {
106 return openReplySet(ctx, root, set, textOnly(call))
107}
108
109// openReplySet is openToolSet for tools whose answers may carry an image.
110func openReplySet(ctx context.Context, root string, set toolSet, call ToolReplyFunc) (*toolSocket, error) {
111 dir, err := os.MkdirTemp(root, toolDirPrefix)
112 if err != nil {
113 return nil, err
114 }
115 fail := func(err error) (*toolSocket, error) { os.RemoveAll(dir); return nil, err }
116 if err = os.Chmod(dir, 0700); err != nil {
117 return fail(err)
118 }
119 path := filepath.Join(dir, toolSocketName)
120 l, err := listenToolSocket(dir, path)
121 if err != nil {
122 return fail(err)
123 }
124 l.SetUnlinkOnClose(false)
125 if err = os.Chmod(path, 0600); err != nil {
126 l.Close()
127 return fail(err)
128 }
129 ctx, cancel := context.WithCancel(ctx)
130 s := &toolSocket{Path: path, dir: dir, listener: l, cancel: cancel, call: call, set: set, peerUID: toolPeerUID}
131 context.AfterFunc(ctx, func() { l.Close() })
132 s.wg.Add(1)
133 go s.accept(ctx)
134 return s, nil
135}
136
137func (s *toolSocket) Close() {
138 s.cancel()
139 s.listener.Close()
140 s.wg.Wait()
141 os.RemoveAll(s.dir)
142}
143
144func (s *toolSocket) accept(ctx context.Context) {
145 defer s.wg.Done()
146 for {
147 c, err := s.listener.AcceptUnix()
148 if err != nil {
149 return
150 }
151 // Only this user's processes may talk to the broker.
152 raw, err := c.SyscallConn()
153 uid, known := uint32(0), false
154 if err == nil {
155 _ = raw.Control(func(fd uintptr) { uid, err = s.peerUID(int(fd)); known = err == nil })
156 }
157 if err != nil || !known || uid != uint32(os.Getuid()) {
158 c.Close()
159 continue
160 }
161 s.wg.Add(1)
162 go func() {
163 defer s.wg.Done()
164 defer c.Close()
165 stop := context.AfterFunc(ctx, func() { c.Close() })
166 defer stop()
167 serveMCP(ctx, c, s.set, s.call)
168 }()
169 }
170}
171
172type mcpRequest struct {
173 JSONRPC string `json:"jsonrpc"`
174 ID json.RawMessage `json:"id,omitempty"`
175 Method string `json:"method"`
176 Params json.RawMessage `json:"params,omitempty"`
177}
178
179// toolSchema is a JSON Schema object; required is always an array (a
180// null there is not valid JSON Schema and the CLI refuses the tool list).
181func toolSchema(props map[string]any, required ...string) map[string]any {
182 if required == nil {
183 required = []string{}
184 }
185 return map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false}
186}
187
188var str = map[string]string{"type": "string"}
189
190// converseTools are the coordinator's tools as the model sees them. The
191// descriptions are for the model; people never read them.
192var converseTools = []any{
193 map[string]any{"name": wire.ToolRequestAccess, "description": "Propose an access request for an unreachable repository. The person confirms before filing; never retry unprompted. Prefer one repository; namespace only if explicitly requested. Role defaults to agent.", "inputSchema": toolSchema(map[string]any{"target": str, "role": str, "reason": str}, "target", "reason")},
194 map[string]any{"name": "status", "description": "Read-only: this person's runner, model connections, current projects, the repositories you can add (can_add), the namespaces you can create repositories in (create_in, with home for unrelated new work), and the team's active specialists (specialists: id, profile, name, brief, and scope, team or the one project it works on; pass the id as start_task's specialist). Call it before choosing where work goes. runner.tools says whether the runner's pinned preview scanner is installed and matches its pin (ok, missing, mismatch, unpinned, or unknown when the runner does not say): a preview that failed for its scanner needs the runner fixed or updated, not another try. runner.tools.carlos says whether its CARLOS command line tool is current enough for previews and sites (ok, outdated, missing) and carlos_version which release it is: outdated or missing needs the person to update it, not another try. runner.tools.renderer, only on a runner that has the page renderer, says whether its pinned browser is installed, matches its pin and has rendered its check page since the runner started (ok, missing, mismatch, unpinned): anything but ok needs the runner updated, not another try.", "inputSchema": toolSchema(map[string]any{})},
195 map[string]any{"name": "find", "description": "Read-only: find which repository an app, product or feature lives in, by name, alias or keyword (for example Woodstar). Returns candidates with reasons, or says nothing Equipo's agent can reach matches.", "inputSchema": toolSchema(map[string]any{"query": str}, "query")},
196 map[string]any{"name": "search_code", "description": "Read-only: search a repository's default branch for a fixed string, case insensitive. Returns path:line: text, bounded.", "inputSchema": toolSchema(map[string]any{"repo": str, "query": str}, "repo", "query")},
197 map[string]any{"name": "read_file", "description": "Read-only: read a file from a repository's default branch with line numbers (up to 300 lines from start), or list a directory (empty path is the root). For a file the person attached, repo is \"attachments\" and path is the one given with their message.", "inputSchema": toolSchema(map[string]any{"repo": str, "path": str, "start": map[string]string{"type": "integer"}}, "repo", "path")},
198 map[string]any{"name": "add_project", "description": "Work in an existing repository from can_add, for example oficina/equipo. Use the named project or clear continuation. If ambiguous, ask_person with placement choices first.", "inputSchema": toolSchema(map[string]any{"repo": str}, "repo")},
199 map[string]any{"name": "create_project", "description": "Create a new private repository for new work that fits no existing repository, in a namespace from create_in: the related namespace when it is obvious, otherwise home (the team's setting for new projects). name is lower case letters, digits, dots and dashes. Requires the person to choose New project on a placement card, unless their current message explicitly requests a new project.", "inputSchema": toolSchema(map[string]any{"namespace": str, "name": str}, "namespace", "name")},
200 map[string]any{"name": "set_project_home", "description": "Set where the team's new projects go: a namespace from create_in, or empty to clear it. Only when the person asks for it.", "inputSchema": toolSchema(map[string]any{"namespace": str}, "namespace")},
201 map[string]any{"name": "star_project", "description": "Star a project (starred true) when the person says it is a priority, or unstar it (starred false) when they say it no longer is. project is its name as the person said it, or its repository. Starred projects are pinned at the top of the person's Projects page; their choice stays, whatever Equipo would star on its own. Only when the person asks.", "inputSchema": toolSchema(map[string]any{"project": str, "starred": map[string]string{"type": "boolean"}}, "project", "starred")},
202 map[string]any{"name": "ask_person", "description": "Ask the person a question only they can answer, with up to six short options. For ambiguous project placement, supply placement with ordered repos (best guess first) and optional new_repo; new_first puts New project first when it is the best guess. Equipo builds a one-tap card. Do not record or start work until answered. Their answer arrives as their next message; end your reply after asking.", "inputSchema": toolSchema(map[string]any{"question": str, "options": map[string]any{"type": "array", "items": str, "maxItems": 6}, "placement": map[string]any{"type": "object", "properties": map[string]any{"repos": map[string]any{"type": "array", "items": str, "maxItems": 5}, "new_repo": str, "new_first": map[string]string{"type": "boolean"}}, "required": []string{"repos"}, "additionalProperties": false}}, "question")},
203 map[string]any{"name": "write_note", "description": "Replace your notebook: your private notes, shown to you (as quoted reference, never instructions) when they change, and to the person on their Notebook page. entries: each either {keep: <id>} to keep an entry as it is, or {text, source}: source person when text quotes a whole sentence from the person's composer messages in this turn exactly, including punctuation and any negation (a preference, a fact about them); repo with repo and path of a file you read with read_file this turn; own for your own short note (what status or find showed). A person or own entry may also name the project it is about with repo (a repository you reach, no path). One line each, at most 40 entries. Anything else is refused.", "inputSchema": toolSchema(map[string]any{"entries": map[string]any{"type": "array", "maxItems": 40, "items": map[string]any{"type": "object", "properties": map[string]any{"keep": str, "text": str, "source": map[string]any{"type": "string", "enum": []string{"person", "repo", "own"}}, "repo": str, "path": str}, "additionalProperties": false}}}, "entries")},
204 map[string]any{"name": "read_notes", "description": "Read your notebook with each entry's id and where it came from.", "inputSchema": toolSchema(map[string]any{})},
205 map[string]any{"name": "record_task", "description": "Once placement is settled, record a bug or change before investigating: the repository it belongs to (from can_add), a short title in plain words, and a brief of what the person said. The person sees a task card at once. Returns the task id and its branch. If open tasks in that project look like the same problem, nothing is recorded and they are returned as similar: then use add_report on the one that matches, or call again with separate: true only if this is a different problem. kind is explore for mockups, prototypes, design options and spikes (they end at a preview and the person's choice, never a merge), change (the default) for anything meant to ship.", "inputSchema": toolSchema(map[string]any{"repo": str, "title": str, "brief": str, "separate": map[string]string{"type": "boolean"}, "kind": map[string]any{"type": "string", "enum": []string{"change", "explore"}}, "priority": priorityArg, "by": byArg}, "repo", "title", "brief")},
206 map[string]any{"name": "add_finding", "description": "Attach what you found while investigating to a task: a headline, one sentence for the person in plain words with no file paths (for example \"Found it: hiding the navigation bar turned off swipe-back.\"); the finding itself in full; and the repository, file path and line it points at when there is one. The task moves to investigated.", "inputSchema": toolSchema(map[string]any{"task": str, "headline": str, "text": str, "repo": str, "path": str, "line": map[string]string{"type": "integer"}}, "task", "headline", "text")},
207 map[string]any{"name": "start_task", "description": "Hand a recorded task to Engineering, who changes the code on the task's own branch and pushes it to Amadan. brief is what to change and why, from your findings. specialist is optional: the id of an active specialist from status that makes changes (Design) and covers the task's project or the team, to do the task instead of Engineering; its fix rounds and retries stay with it. Never merges and never opens a pull request. Call it once per task.", "inputSchema": toolSchema(map[string]any{"task": str, "brief": str, "priority": priorityArg, "by": byArg, "specialist": str}, "task", "brief")},
208 map[string]any{"name": "read_task", "description": "Read a task: its stage, findings, steps (state, branch, commit, summary) and the person's notes on it.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")},
209 map[string]any{"name": "cancel_task", "description": "Cancel a task when the person asks; a running step stops.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")},
210 map[string]any{"name": "add_report", "description": "Add the person's new report of a problem that is already an open task (from record_task's similar list, or one you know) to that task, instead of recording a duplicate. text is what the person said. The person sees the task card.", "inputSchema": toolSchema(map[string]any{"task": str, "text": str}, "task", "text")},
211 map[string]any{"name": "hold_merge", "description": "Stop Equipo merging this task on its own when you have a concrete reason it needs the person's look (reason: one plain sentence, shown on their merge card). It can only make Equipo more careful: the person's own Merge still merges. There is no tool to lift a hold.", "inputSchema": toolSchema(map[string]any{"task": str, "reason": str}, "task", "reason")},
212 map[string]any{"name": "set_merge_policy", "description": "Record how Equipo merges a project, from what the person said (words: their sentence). mode is rules (merge on its own when every rule holds) or ask (ask before every merge); max_lines and max_files bound a merge without checks; main_ships is yes or no (does merging to main ship to users); add_sensitive adds path globs that always ask. A stricter change applies at once; a looser one waits for the person to tap Save on a card.", "inputSchema": toolSchema(map[string]any{"project": str, "words": str, "mode": str, "max_lines": map[string]any{"type": "integer"}, "max_files": map[string]any{"type": "integer"}, "main_ships": str, "add_sensitive": map[string]any{"type": "array", "items": str}}, "project", "words")},
213 map[string]any{"name": "propose_specialist", "description": "Ask the person to add a specialist to their team, from Equipo's fixed menu, when the work needs one that status does not list. Two profiles. research-v1, when the person wants something researched on the public web: it reads public web pages Equipo fetches for a task and reports what they say, and never reaches repositories; pass a short name (for example Research), a brief of at most 2 KB on what it should look for, capabilities [\"web.research\"] and tools [\"submit_findings\", \"keep_image\"], exactly those, for the whole team (no project). design-v1, for visual design, layout, themes and mockups: it changes the design on a task's own branch and looks at its pages in a browser with no network, and never merges or publishes; pass a short name (for example Design), a brief of at most 2 KB from the person's words on the look they want, capabilities [\"branch.edit\", \"page.render\"] and tools [\"render_page\", \"submit_candidate\", \"ask_person\"], exactly those, and project: the one project it is for (its name or id), or leave project out for the whole team. Nothing is added until an owner taps Add on the card it raises; do not ask again in your reply. After an Add for one project, Equipo carries on with the request itself. If they tap Not now, it cannot be proposed again for 7 days.", "inputSchema": toolSchema(map[string]any{"profile": map[string]any{"type": "string", "enum": []string{"research-v1", "design-v1"}}, "name": str, "brief": str, "capabilities": map[string]any{"type": "array", "items": str}, "tools": map[string]any{"type": "array", "items": str}, "project": str}, "profile", "name", "brief", "capabilities", "tools")},
214 map[string]any{"name": "research", "description": "Ask Research (once it is on the team; see propose_specialist) to read public web pages for one of the person's tasks. Use it when an exploration or change names an outside site, brand, API or docs, or the person asking (their business, their own site), and the work needs what those pages say. task is the task id; question (at most 1,000 bytes) is what to look for, for example colours, logo, fonts, opening hours and services; urls are pages you propose (https or http, no query string, a path of at most 100 characters, at most 10), or []. URLs and bare domains the person typed on the task are read without asking; your urls are shown to the person in full on a card and read only if they tap Allow, so propose only pages the task needs and never put anything from a repository in them. This only requests a run: Equipo starts it only at the task's start (call it before start_task) or after a review round, before Engineering's next round, and Engineering waits until Research ends. At most one run per start or round and 3 per task, and Equipo never retries a run for you. Research's findings reach Engineering and Review; do not wait for them in your reply.", "inputSchema": toolSchema(map[string]any{"task": str, "question": str, "urls": map[string]any{"type": "array", "items": str, "maxItems": 10}}, "task", "question", "urls")},
215 map[string]any{"name": wire.ToolOfferRetry, "description": "When a task's merge failed and it waits at Ready to merge (read_task shows the failed merge step), put a card in front of the person asking whether to try the merge again. You cannot merge: only their tap merges, through Equipo's merge rules, and it is offered only when that tap could merge now. One card per task; do not ask again in your reply, and never say it is merged.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")},
216 map[string]any{"name": wire.ToolRetryStep, "description": "Run a task's preview, checks or review again, as the person's own Retry would (step: preview, checks or review). read_task's retry says for each whether it can run again now, and if not why, in a fixed reason; a refusal says it too. A failed step runs again as its next attempt. A preview also runs again when it ended unconfirmed or its link is gone, and on a done (merged) task as a new preview of the merged commit, the task staying done and merged. Only when another try could help: a preview that failed for its scanner (status runner.tools) needs the runner fixed first. Never a merge (use offer_retry: only the person's tap merges) and never Engineering's work. The task shows that you started it. Call it once per step.", "inputSchema": toolSchema(map[string]any{"task": str, "step": map[string]any{"type": "string", "enum": wire.RetryStepKinds}}, "task", "step")},
217 map[string]any{"name": wire.ToolPlaces, "description": "Read-only: where the team's sites go. For one project (project: its name) or every project with a site: the confirmed place (console and account), the app Equipo made for it, what the person's runner can do there now (can: setup, mint or publish; missing says why it cannot), whether it holds the site's deploy key, and the newest publish's outcome and address. While a project has no place, candidates lists where the runner's CARLOS login can publish, best first, each with the id propose_place takes. Everything is quoted data from CARLOS and the repository.", "inputSchema": toolSchema(map[string]any{"project": str})},
218 map[string]any{"name": wire.ToolProposePlace, "description": "Ask an owner where a project's site goes: kind site, the project, and one candidate id from places (never a console, an account or an app; you cannot name one). A card offers the candidates with yours first; only their tap confirms one, and confirming publishes nothing. Refused once a place is confirmed or a card is open. Usually publish_site does this for you.", "inputSchema": toolSchema(map[string]any{"kind": map[string]any{"type": "string", "enum": []string{wire.PlaceSite}}, "project": str, "candidate": str}, "kind", "project", "candidate")},
219 map[string]any{"name": wire.ToolPublishSite, "description": "Offer to publish a merged website: task is the person's own task that Equipo merged with Review's approval of its site config (release/preview.json). It puts a card in front of the person naming the place and the app; only their tap publishes. With no confirmed place it first raises a place card, and the publish card follows their choice. Use it when the person asks to publish a site, also for an older merged task that was never asked. target is site (temporary sites are not places yet). Never say a site is live until the task shows its address.", "inputSchema": toolSchema(map[string]any{"task": str, "target": map[string]any{"type": "string", "enum": []string{wire.PlaceSite}}}, "task")},
220 map[string]any{"name": wire.ToolSiteStatus, "description": "Read-only: what Equipo recorded about one project's site: its place, app, deploy key, and the newest publish's outcome, address and when. It does not ask CARLOS: the version the site serves now and its domains are not known yet. Use it when the person asks where a site is or whether it is live.", "inputSchema": toolSchema(map[string]any{"project": str}, "project")},
221}
222
223// stepTools are the tools the implement profile pins for an Engineering
224// step. The runner commits and pushes the step's changes itself, so they
225// only tell the model so.
226var stepTools = []any{
227 map[string]any{"name": "submit_candidate", "description": "Not needed: when you finish, Equipo commits your changes in /workspace and pushes them. End with a short summary instead.", "inputSchema": toolSchema(map[string]any{})},
228 map[string]any{"name": "ask_person", "description": "Nobody can answer during this step. Make the most reasonable choice and say so in your summary.", "inputSchema": toolSchema(map[string]any{"question": str}, "question")},
229 map[string]any{"name": "submit_render", "description": "Not available in this step.", "inputSchema": toolSchema(map[string]any{})},
230}
231
232// stepToolText is the answer to any step tool.
233const stepToolText = "Not needed in this step: Equipo commits and pushes your changes in /workspace when you finish. Carry on, and end with a short summary of what you changed and why."
234
235// designTools are the tools the design_step profile pins for a Design
236// step: exactly design-v1's (provider.DesignTools). The Design step
237// answers them (designstep.Attempt): render_page behind the instance's
238// render check, submit_candidate's options, and ask_person's fixed
239// reply; the runner commits and pushes the work itself, as
240// Engineering's.
241var designTools = []any{
242 map[string]any{"name": "render_page", "description": "Render pages of the task's site in a browser: tree base (the task's base commit) or work (your workspace now); compare true renders both trees, whichever tree you name or none, and diffs them. Each capture is a PNG in /render/, read-only to you; open it with Read.", "inputSchema": toolSchema(map[string]any{"tree": map[string]any{"type": "string", "enum": []string{"base", "work"}}, "pages": map[string]any{"type": "array", "minItems": 1, "maxItems": 6, "items": toolSchema(map[string]any{"path": str, "viewport": map[string]any{"type": "string", "enum": []string{"phone", "tablet", "desktop"}}, "full_page": map[string]string{"type": "boolean"}}, "path", "viewport")}, "compare": map[string]string{"type": "boolean"}}, "pages")},
243 map[string]any{"name": "submit_candidate", "description": "Submit your options: for each, in the order of the options page, its name and the captures that show it best, by the file names render_page gave under /render/ in this step. At most 4 options and 12 captures in all; a later call replaces an earlier one. Equipo still commits and pushes your workspace when you finish.", "inputSchema": toolSchema(map[string]any{"options": map[string]any{"type": "array", "maxItems": wire.MaxDesignOptions, "items": toolSchema(map[string]any{"name": str, "captures": map[string]any{"type": "array", "items": str, "maxItems": wire.MaxDesignCaptures}}, "name", "captures")}}, "options")},
244 map[string]any{"name": "ask_person", "description": "Nobody can answer during this step. Make the most reasonable choice, build it, and say so in your summary.", "inputSchema": toolSchema(map[string]any{"question": str}, "question")},
245}
246
247// designToolNames are designTools' names, in order.
248var designToolNames = []string{"render_page", "submit_candidate", "ask_person"}
249
250// designRun is a Design step's run on binding b: the design_step policy
251// (design-v1's tools, Engineering's native tools and /render read-only,
252// claude.DesignPermission) with prompt, its tools answered by call. The
253// caller sets render, the step's capture directory.
254func designRun(b runner.AccountBinding, prompt string, call ToolFunc) specialistRun {
255 return specialistRun{action: provider.DesignStepAction, binding: b, tools: designTools, names: designToolNames, permission: claude.DesignPermission, call: call, prompt: prompt}
256}
257
258// serveMCP answers JSON-RPC lines until the peer closes.
259func serveMCP(ctx context.Context, c net.Conn, set toolSet, call ToolReplyFunc) {
260 r := bufio.NewReaderSize(c, maxToolFrame+1)
261 enc := json.NewEncoder(c)
262 initialized := false
263 for {
264 line, err := r.ReadSlice('\n')
265 if err != nil || len(line) > maxToolFrame {
266 return
267 }
268 var q mcpRequest
269 if json.Unmarshal(line, &q) != nil || q.JSONRPC != "2.0" {
270 return
271 }
272 if len(q.ID) == 0 {
273 continue
274 }
275 active := set
276 if set.current != nil {
277 active = set.current()
278 }
279 reply := map[string]any{"jsonrpc": "2.0", "id": q.ID}
280 switch q.Method {
281 case "initialize":
282 var p struct {
283 ProtocolVersion string `json:"protocolVersion"`
284 }
285 _ = json.Unmarshal(q.Params, &p)
286 if !slices.Contains([]string{"2024-11-05", "2025-03-26", "2025-06-18"}, p.ProtocolVersion) {
287 p.ProtocolVersion = "2025-06-18"
288 }
289 initialized = true
290 reply["result"] = map[string]any{"protocolVersion": p.ProtocolVersion, "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo-runner", "version": "2"}}
291 case "ping":
292 reply["result"] = map[string]any{}
293 case "tools/list":
294 if !initialized {
295 reply["error"] = map[string]any{"code": -32600, "message": "not initialized"}
296 break
297 }
298 tools := slices.Clone(active.list)
299 if active.permission != nil {
300 permission := map[string]any{"name": "permission", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"tool_name": map[string]string{"type": "string"}, "tool_use_id": map[string]string{"type": "string"}, "input": map[string]string{"type": "object"}}, "required": []string{"tool_name", "input"}, "additionalProperties": false}}
301 tools = append([]any{permission}, tools...)
302 }
303 reply["result"] = map[string]any{"tools": tools}
304 case "tools/call":
305 var p struct {
306 Name string `json:"name"`
307 Arguments json.RawMessage `json:"arguments"`
308 Meta map[string]any `json:"_meta"`
309 }
310 if !initialized || json.Unmarshal(q.Params, &p) != nil {
311 reply["error"] = map[string]any{"code": -32602, "message": "unavailable"}
312 break
313 }
314 if p.Name == "permission" && active.permission != nil {
315 reply["result"] = map[string]any{"content": []any{map[string]string{"type": "text", "text": active.permission(p.Arguments)}}}
316 break
317 }
318 if call == nil || !slices.Contains(active.names, p.Name) {
319 reply["error"] = map[string]any{"code": -32602, "message": "unavailable"}
320 break
321 }
322 useID, _ := p.Meta["claudecode/toolUseId"].(string)
323 if len(p.Arguments) == 0 || string(p.Arguments) == "null" {
324 p.Arguments = json.RawMessage("{}")
325 }
326 out := call(ctx, p.Name, useID, p.Arguments)
327 content := []any{map[string]string{"type": "text", "text": out.Text}}
328 if out.Image != nil {
329 content = append(content, map[string]string{"type": "image", "data": base64.StdEncoding.EncodeToString(out.Image.Data), "mimeType": out.Image.MediaType})
330 }
331 reply["result"] = map[string]any{"content": content, "isError": out.IsError}
332 default:
333 reply["error"] = map[string]any{"code": -32601, "message": "unavailable"}
334 }
335 if enc.Encode(reply) != nil {
336 return
337 }
338 }
339}
340
341// permissionText allows only the conversation's own Equipo tools (names,
342// the lane's); every other request (native tools, the other lane's
343// tools, anything unexpected) is denied.
344func permissionText(raw json.RawMessage, names []string) string {
345 var in struct {
346 ToolName string `json:"tool_name"`
347 Input json.RawMessage `json:"input"`
348 }
349 text := `{"behavior":"deny","message":"Only Equipo's own tools are available to the coordinator."}`
350 if json.Unmarshal(raw, &in) == nil && strings.HasPrefix(in.ToolName, "mcp__equipo__") && slices.Contains(names, strings.TrimPrefix(in.ToolName, "mcp__equipo__")) {
351 allow, _ := json.Marshal(map[string]any{"behavior": "allow", "updatedInput": in.Input})
352 text = string(allow)
353 }
354 return text
355}
356
357// priorityArg and byArg are record_task's and start_task's scheduler
358// fields (connectors spec §6): set only from what the person said, when
359// the task is created; the person alone makes a task urgent or changes
360// them later.
361var (
362 priorityArg = map[string]any{"type": "string", "enum": []string{"low", "normal"}, "description": "low when the person said it can wait, normal otherwise (the default). Never urgent: only the person marks a task urgent."}
363 byArg = map[string]any{"type": "string", "description": "A deadline the person gave, as a date (2026-11-20) or a time (RFC 3339). Leave it out when they gave none."}
364)
365