oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package runner
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/hex"
8 "encoding/json"
9 "io"
10 "path/filepath"
11 "slices"
12 "strings"
13 "unicode/utf8"
14
15 "amadan.net/oficina/equipo/internal/coordinator"
16 "amadan.net/oficina/equipo/internal/runner/mcpresource"
17 "amadan.net/oficina/equipo/internal/runnerproto"
18 "amadan.net/oficina/equipo/internal/taskplan"
19)
20
21type ToolCopy struct {
22 Coordinator map[string]string `json:"coordinator,omitempty"`
23 Acceptance string `json:"acceptance"`
24 Answer string `json:"answer"`
25 Render string `json:"render"`
26 Accepted string `json:"accepted"`
27 Rejected string `json:"rejected"`
28 Ask string `json:"ask"`
29 Candidate string `json:"candidate"`
30 Review string `json:"review"`
31 Reproduction string `json:"reproduction"`
32}
33
34type CandidateSubmission struct {
35 Commit string `json:"commit"`
36}
37type ReviewSubmission struct {
38 Candidate string `json:"candidate"`
39 Decision string `json:"decision"`
40 Findings []string `json:"findings"`
41}
42type PersonQuestion struct {
43 Question string `json:"question"`
44}
45
46func validateToolArguments(name string, raw json.RawMessage) error {
47 decode := func(v any) error { return runnerproto.DecodeLimit(bytes.NewReader(raw), v, maxToolFrame) }
48 commit := func(v string) bool {
49 b, err := hex.DecodeString(v)
50 return err == nil && len(b) == 20 && strings.ToLower(v) == v
51 }
52 switch name {
53 case "ask_person":
54 var v PersonQuestion
55 if decode(&v) != nil || strings.TrimSpace(v.Question) == "" || len(v.Question) > 8192 || !utf8.ValidString(v.Question) {
56 return runnerproto.ErrInvalid
57 }
58 case "submit_answer":
59 var v taskplan.AnswerResult
60 if decode(&v) != nil || taskplan.ValidateAnswer(v) != nil {
61 return runnerproto.ErrInvalid
62 }
63 case "submit_candidate", "submit_render":
64 var v CandidateSubmission
65 if decode(&v) != nil || !commit(v.Commit) {
66 return runnerproto.ErrInvalid
67 }
68 case "submit_review":
69 var v ReviewSubmission
70 if decode(&v) != nil || !commit(v.Candidate) || !slices.Contains([]string{"approve", "changes_requested"}, v.Decision) || len(v.Findings) > 64 {
71 return runnerproto.ErrInvalid
72 }
73 for _, f := range v.Findings {
74 if len(f) > 4096 {
75 return runnerproto.ErrInvalid
76 }
77 }
78 case "submit_reproduction", "submit_acceptance":
79 var v runnerproto.Reproduction
80 if decode(&v) != nil || strings.TrimSpace(v.ExpectedSymptom) == "" || len(v.ExpectedSymptom) > 8192 || len(v.Files) == 0 || len(v.Files) > 32 || len(v.TestNames) == 0 {
81 return runnerproto.ErrInvalid
82 }
83 for _, test := range v.TestNames {
84 if strings.TrimSpace(test.Package) == "" || strings.TrimSpace(test.Name) == "" || !utf8.ValidString(test.Package) || !utf8.ValidString(test.Name) {
85 return runnerproto.ErrInvalid
86 }
87 }
88 seen := map[string]bool{}
89 for _, f := range v.Files {
90 if f.Path == "" || filepath.IsAbs(f.Path) || filepath.Clean(f.Path) != f.Path || strings.HasPrefix(f.Path, "../") || f.Path == ".." || strings.Contains(f.Path, "\\") || slices.Contains(strings.Split(f.Path, "/"), ".git") || seen[f.Path] || len(f.Bytes) == 0 {
91 return runnerproto.ErrInvalid
92 }
93 seen[f.Path] = true
94 }
95 default:
96 return runnerproto.ErrInvalid
97 }
98 return nil
99}
100
101type mcpRequest struct {
102 JSONRPC string `json:"jsonrpc"`
103 ID json.RawMessage `json:"id,omitempty"`
104 Method string `json:"method"`
105 Params json.RawMessage `json:"params,omitempty"`
106}
107type mcpResponse struct {
108 JSONRPC string `json:"jsonrpc"`
109 ID json.RawMessage `json:"id"`
110 Result any `json:"result,omitempty"`
111 Error any `json:"error,omitempty"`
112}
113
114func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPath, capabilityPath string) error {
115 if !filepath.IsAbs(socketPath) || len(socketPath) > 107 || filepath.Dir(socketPath) != filepath.Dir(capabilityPath) {
116 return runnerproto.ErrInvalid
117 }
118 if _, err := readToolCapability(capabilityPath); err != nil {
119 return err
120 }
121 return serveTools(ctx, input, output, func() (toolCapability, error) { return readToolCapability(capabilityPath) }, func(q toolRequest) (any, error) {
122 err := callToolSocket(ctx, socketPath, q)
123 return nil, err
124 }, nil)
125}
126
127func serveTools(ctx context.Context, input io.Reader, output io.Writer, capability func() (toolCapability, error), call func(toolRequest) (any, error), permission func(context.Context, json.RawMessage) (json.RawMessage, error)) error {
128 reader := bufio.NewReaderSize(input, maxToolFrame+1)
129 encoder := json.NewEncoder(output)
130 initialized := false
131 for {
132 // Peek distinguishes a clean stdio shutdown from an unterminated frame.
133 if _, err := reader.Peek(1); err == io.EOF {
134 return nil
135 } else if err != nil {
136 return runnerproto.ErrInvalid
137 }
138 raw, err := readToolFrame(reader)
139 if err != nil {
140 return err
141 }
142 var q mcpRequest
143 if runnerproto.DecodeLimit(bytes.NewReader(raw), &q, maxToolFrame) != nil || q.JSONRPC != "2.0" {
144 return runnerproto.ErrInvalid
145 }
146 if len(q.ID) == 0 {
147 continue
148 }
149 var id any
150 if json.Unmarshal(q.ID, &id) != nil {
151 return runnerproto.ErrInvalid
152 }
153 switch id.(type) {
154 case string, float64:
155 default:
156 return runnerproto.ErrInvalid
157 }
158 cap, err := capability()
159 if err != nil {
160 return err
161 }
162 var result any
163 switch q.Method {
164 case "initialize":
165 var params struct {
166 ProtocolVersion string `json:"protocolVersion"`
167 Capabilities json.RawMessage `json:"capabilities"`
168 ClientInfo json.RawMessage `json:"clientInfo"`
169 }
170 if initialized || runnerproto.DecodeLimit(bytes.NewReader(q.Params), &params, maxToolFrame) != nil || params.ProtocolVersion == "" {
171 err = runnerproto.ErrInvalid
172 break
173 }
174 if !slices.Contains([]string{"2024-11-05", "2025-03-26", "2025-06-18"}, params.ProtocolVersion) {
175 params.ProtocolVersion = "2025-06-18"
176 }
177 initialized = true
178 result = map[string]any{"protocolVersion": params.ProtocolVersion, "capabilities": map[string]any{"tools": map[string]any{}, "resources": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo-runner", "version": "1"}}
179 case "ping":
180 result = map[string]any{}
181 case "resources/list", "resources/templates/list", "resources/read":
182 if !initialized {
183 err = runnerproto.ErrInvalid
184 break
185 }
186 result, err = mcpresource.Result(q.Method, q.Params)
187 case "tools/list":
188 if !initialized {
189 err = runnerproto.ErrInvalid
190 break
191 }
192 schemas := toolSchemas(cap.Tools, cap.Copy)
193 if cap.Coordinator {
194 schemas = []any{}
195 for _, schema := range coordinator.Schemas(cap.Copy.Coordinator) {
196 schemas = append(schemas, schema)
197 }
198 }
199 if permission != nil {
200 schemas = append(schemas, 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}})
201 }
202 result = map[string]any{"tools": schemas}
203 case "tools/call":
204 if !initialized {
205 err = runnerproto.ErrInvalid
206 break
207 }
208 var params struct {
209 Name string `json:"name"`
210 Meta json.RawMessage `json:"_meta,omitempty"`
211 Arguments map[string]json.RawMessage `json:"arguments"`
212 }
213 if runnerproto.DecodeLimit(bytes.NewReader(q.Params), &params, maxToolFrame) != nil {
214 err = runnerproto.ErrInvalid
215 break
216 }
217 if params.Name == "permission" && permission != nil {
218 raw, _ := json.Marshal(params.Arguments)
219 var answer json.RawMessage
220 answer, err = permission(ctx, raw)
221 if err == nil {
222 result = map[string]any{"content": []any{map[string]string{"type": "text", "text": string(answer)}}}
223 }
224 break
225 }
226 if !slices.Contains(cap.Tools, params.Name) {
227 err = runnerproto.ErrInvalid
228 break
229 }
230 var requestID string
231 if json.Unmarshal(params.Arguments["request_id"], &requestID) != nil || requestID == "" {
232 err = runnerproto.ErrInvalid
233 break
234 }
235 delete(params.Arguments, "request_id")
236 args, encodeErr := json.Marshal(params.Arguments)
237 if encodeErr != nil {
238 err = runnerproto.ErrInvalid
239 break
240 }
241 if cap.Coordinator {
242 _, err = coordinator.Validate(runnerproto.CoordinatorToolCall{RequestID: requestID, Name: params.Name, Arguments: args})
243 } else {
244 err = validateToolArguments(params.Name, args)
245 }
246 if err != nil {
247 break
248 }
249 result, err = call(toolRequest{Capability: cap.Secret, InstanceID: cap.InstanceID, TaskID: cap.TaskID, Attempt: cap.Attempt, Fence: cap.Fence, RequestID: requestID, Name: params.Name, Arguments: args})
250 if err == nil && result == nil {
251 result = map[string]any{"content": []any{map[string]string{"type": "text", "text": cap.Copy.Accepted}}}
252 }
253 default:
254 err = runnerproto.ErrInvalid
255 }
256 reply := mcpResponse{JSONRPC: "2.0", ID: q.ID, Result: result}
257 if err != nil {
258 reply.Result = nil
259 reply.Error = map[string]any{"code": -32602, "message": cap.Copy.Rejected}
260 }
261 if encoder.Encode(reply) != nil {
262 return runnerproto.ErrInvalid
263 }
264 }
265}
266func toolSchemas(names []string, copy ToolCopy) []any {
267 out := []any{}
268 for _, name := range names {
269 props := map[string]any{"request_id": map[string]any{"type": "string", "minLength": 1, "maxLength": 256}}
270 required := []string{"request_id"}
271 description := ""
272 field := func(key string, schema any) { props[key] = schema; required = append(required, key) }
273 text := map[string]any{"type": "string"}
274 commit := map[string]any{"type": "string", "pattern": "^[a-f0-9]{40}$"}
275 switch name {
276 case "ask_person":
277 description = copy.Ask
278 field("question", text)
279 case "submit_candidate", "submit_render":
280 description = copy.Candidate
281 if name == "submit_render" {
282 description = copy.Render
283 }
284 field("commit", commit)
285 case "submit_review":
286 description = copy.Review
287 field("candidate", commit)
288 field("decision", map[string]any{"type": "string", "enum": []string{"approve", "changes_requested"}})
289 field("findings", map[string]any{"type": "array", "items": text})
290 case "submit_reproduction", "submit_acceptance":
291 description = copy.Reproduction
292 if name == "submit_acceptance" {
293 description = copy.Acceptance
294 }
295 field("expected_symptom", text)
296 field("files", map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"path": text, "bytes": text}, "required": []string{"path", "bytes"}, "additionalProperties": false}})
297 field("test_names", map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"package": text, "name": text}, "required": []string{"package", "name"}, "additionalProperties": false}})
298 case "submit_answer":
299 description = copy.Answer
300 field("body", text)
301 field("sources", map[string]any{"type": "array", "minItems": 1, "maxItems": 100, "items": map[string]any{"type": "object", "properties": map[string]any{"kind": text, "id": text, "hash": map[string]any{"type": "string", "pattern": "^[a-f0-9]{64}$"}, "revision": map[string]any{"type": "integer", "minimum": 1}}, "required": []string{"kind", "id", "hash", "revision"}, "additionalProperties": false}})
302
303 default:
304 continue
305 }
306 out = append(out, map[string]any{"name": name, "description": description, "inputSchema": map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false}})
307 }
308 return out
309}
310