| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "slices" |
| 12 | "sync" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 17 | ) |
| 18 | |
| 19 | const directMCP = `{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}` |
| 20 | |
| 21 | // ToolProxy exposes MCP only. The authenticating broker and its capability stay |
| 22 | // in the runner; neither is written into the mounted endpoint directory. |
| 23 | type ToolProxy struct { |
| 24 | coordinator *coordinatorBroker |
| 25 | SocketPath string |
| 26 | broker *AttemptSocket |
| 27 | listener *net.UnixListener |
| 28 | ctx context.Context |
| 29 | cancel context.CancelFunc |
| 30 | workers sync.WaitGroup |
| 31 | once sync.Once |
| 32 | directory string |
| 33 | } |
| 34 | |
| 35 | func OpenToolProxy(ctx context.Context, b ToolBinding) (*ToolProxy, error) { |
| 36 | if b.Journal == nil { |
| 37 | return nil, runnerproto.ErrInvalid |
| 38 | } |
| 39 | return openToolProxy(ctx, b, filepath.Dir(b.Journal.path)) |
| 40 | } |
| 41 | func openToolProxy(ctx context.Context, b ToolBinding, root string) (*ToolProxy, error) { |
| 42 | if b.Journal == nil || b.Current == nil || b.InstanceID == "" || b.TaskID == "" || b.Attempt <= 0 || b.Fence <= 0 || b.Isolation.Status != "confined" || b.Copy.Accepted == "" || b.Copy.Rejected == "" || len(b.Tools) == 0 || !time.Now().Before(b.LeaseDeadline) { |
| 43 | return nil, runnerproto.ErrInvalid |
| 44 | } |
| 45 | for _, name := range b.Tools { |
| 46 | if !slices.Contains([]string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction", "submit_acceptance", "submit_answer", "submit_render"}, name) { |
| 47 | return nil, runnerproto.ErrInvalid |
| 48 | } |
| 49 | } |
| 50 | if err := b.Current(ctx); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | parent, err := openPrivateDir(root) |
| 54 | if err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | parent.Close() |
| 58 | dir, err := os.MkdirTemp(root, "tool-") |
| 59 | if err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | ok := false |
| 63 | defer func() { |
| 64 | if !ok { |
| 65 | os.Remove(filepath.Join(dir, "equipo.sock")) |
| 66 | os.Remove(dir) |
| 67 | } |
| 68 | }() |
| 69 | fd, err := openPrivateDir(dir) |
| 70 | if err != nil { |
| 71 | return nil, err |
| 72 | } |
| 73 | defer fd.Close() |
| 74 | path := filepath.Join(dir, "equipo.sock") |
| 75 | listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd()), Net: "unix"}) |
| 76 | if err != nil { |
| 77 | return nil, err |
| 78 | } |
| 79 | listener.SetUnlinkOnClose(false) |
| 80 | if err = os.Chmod(path, 0600); err != nil { |
| 81 | listener.Close() |
| 82 | return nil, err |
| 83 | } |
| 84 | ctx, cancel := context.WithCancel(ctx) |
| 85 | b.Tools = slices.Clone(b.Tools) |
| 86 | broker := &AttemptSocket{pending: b.Session.AttemptKey == "", binding: b, done: make(chan struct{}), capability: toolCapability{Secret: rand.Text() + rand.Text(), Copy: b.Copy, Tools: b.Tools, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence}} |
| 87 | p := &ToolProxy{SocketPath: path, broker: broker, listener: listener, ctx: ctx, cancel: cancel, directory: dir} |
| 88 | p.workers.Add(2) |
| 89 | go p.accept() |
| 90 | // Cancellation closes all connections and permanently invalidates the broker. |
| 91 | context.AfterFunc(ctx, func() { _ = p.Close() }) |
| 92 | go func() { |
| 93 | defer p.workers.Done() |
| 94 | tick := time.NewTicker(100 * time.Millisecond) |
| 95 | defer tick.Stop() |
| 96 | for { |
| 97 | select { |
| 98 | case <-ctx.Done(): |
| 99 | return |
| 100 | case <-tick.C: |
| 101 | broker.mu.Lock() |
| 102 | b := broker.binding |
| 103 | var err error |
| 104 | if broker.invalid || !time.Now().Before(b.LeaseDeadline) { |
| 105 | err = runnerproto.ErrInvalid |
| 106 | } |
| 107 | if err == nil && b.Session.AttemptKey != "" { |
| 108 | var recovered int |
| 109 | err = b.Journal.db.QueryRowContext(ctx, "SELECT recovered FROM direct_attempts WHERE attempt=?", b.Session.AttemptKey).Scan(&recovered) |
| 110 | if recovered != 0 { |
| 111 | err = runnerproto.ErrInvalid |
| 112 | } |
| 113 | } |
| 114 | broker.mu.Unlock() |
| 115 | if err != nil { |
| 116 | cancel() |
| 117 | return |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | }() |
| 122 | ok = true |
| 123 | return p, nil |
| 124 | } |
| 125 | |
| 126 | // BindTurn is called by the trusted supervisor after session identity and turn |
| 127 | // identity is durable, before StartTurn writes its prompt. Calls still require |
| 128 | // durable dispatch. Binding never changes the task, fence or tools. |
| 129 | func (p *ToolProxy) BindTurn(session provider.Session, turn string) error { |
| 130 | if p.coordinator != nil { |
| 131 | return p.bindCoordinator(session, turn) |
| 132 | } |
| 133 | s := p.broker |
| 134 | s.mu.Lock() |
| 135 | defer s.mu.Unlock() |
| 136 | if s.invalid || p.ctx.Err() != nil || s.binding.Agent.Provider != session.Provider { |
| 137 | return runnerproto.ErrInvalid |
| 138 | } |
| 139 | if s.binding.Session.AttemptKey != "" && s.binding.Session != session { |
| 140 | return runnerproto.ErrInvalid |
| 141 | } |
| 142 | if err := s.authorityLocked(p.ctx); err != nil { |
| 143 | return err |
| 144 | } |
| 145 | var saved string |
| 146 | var recovered int |
| 147 | if turn == "" { |
| 148 | return runnerproto.ErrInvalid |
| 149 | } |
| 150 | if err := s.binding.Journal.db.QueryRowContext(p.ctx, "SELECT session,recovered FROM direct_attempts WHERE attempt=?", session.AttemptKey).Scan(&saved, &recovered); err != nil || saved != session.ID || recovered != 0 { |
| 151 | return runnerproto.ErrInvalid |
| 152 | } |
| 153 | if s.binding.TurnID != "" && s.binding.TurnID != turn { |
| 154 | var active int |
| 155 | if err := s.binding.Journal.db.QueryRowContext(p.ctx, "SELECT count(*) FROM direct_turns WHERE attempt=? AND state IN ('intent','dispatched')", session.AttemptKey).Scan(&active); err != nil || active != 0 { |
| 156 | return runnerproto.ErrInvalid |
| 157 | } |
| 158 | } |
| 159 | s.binding.Session = session |
| 160 | s.binding.TurnID = turn |
| 161 | s.binding.Agent.AgentID = session.AttemptKey |
| 162 | s.binding.Agent.ProviderSessionID = session.ID |
| 163 | s.pending = false |
| 164 | return nil |
| 165 | } |
| 166 | |
| 167 | // RenewLease accepts only the supervisor's trusted monotonic renewal. |
| 168 | func (p *ToolProxy) RenewLease(ctx context.Context, deadline time.Time) error { |
| 169 | if p.coordinator != nil { |
| 170 | b := p.coordinator |
| 171 | if err := b.current(ctx, false); err != nil { |
| 172 | return err |
| 173 | } |
| 174 | b.mu.Lock() |
| 175 | defer b.mu.Unlock() |
| 176 | if !deadline.After(b.deadline) || deadline.After(b.binding.Claim.AttemptDeadline) { |
| 177 | return runnerproto.ErrInvalid |
| 178 | } |
| 179 | b.deadline = deadline |
| 180 | return nil |
| 181 | } |
| 182 | return p.broker.RenewLease(ctx, deadline) |
| 183 | } |
| 184 | |
| 185 | func (p *ToolProxy) MCP() json.RawMessage { return json.RawMessage(directMCP) } |
| 186 | func (p *ToolProxy) Close() error { |
| 187 | p.once.Do(func() { |
| 188 | p.cancel() |
| 189 | if p.broker != nil { |
| 190 | p.broker.Invalidate() |
| 191 | } |
| 192 | if p.coordinator != nil { |
| 193 | p.coordinator.mu.Lock() |
| 194 | p.coordinator.invalid = true |
| 195 | p.coordinator.mu.Unlock() |
| 196 | } |
| 197 | p.listener.Close() |
| 198 | }) |
| 199 | p.workers.Wait() |
| 200 | if err := os.Remove(p.SocketPath); err != nil && !os.IsNotExist(err) { |
| 201 | return err |
| 202 | } |
| 203 | if err := os.Remove(p.directory); err != nil && !os.IsNotExist(err) { |
| 204 | return err |
| 205 | } |
| 206 | return nil |
| 207 | } |
| 208 | func (p *ToolProxy) accept() { |
| 209 | defer p.workers.Done() |
| 210 | for { |
| 211 | conn, err := p.listener.AcceptUnix() |
| 212 | if err != nil { |
| 213 | return |
| 214 | } |
| 215 | p.workers.Add(1) |
| 216 | go func() { |
| 217 | defer p.workers.Done() |
| 218 | defer conn.Close() |
| 219 | stop := context.AfterFunc(p.ctx, func() { conn.Close() }) |
| 220 | defer stop() |
| 221 | if !toolPeer(conn) { |
| 222 | return |
| 223 | } |
| 224 | if p.coordinator != nil { |
| 225 | p.serveCoordinator(conn) |
| 226 | return |
| 227 | } |
| 228 | // Cancellation and lease loss close idle connections through AfterFunc. |
| 229 | input := &proxyReader{conn: conn} |
| 230 | _ = serveTools(p.ctx, input, conn, func() (toolCapability, error) { |
| 231 | p.broker.mu.Lock() |
| 232 | defer p.broker.mu.Unlock() |
| 233 | if p.broker.invalid || p.ctx.Err() != nil { |
| 234 | return toolCapability{}, runnerproto.ErrInvalid |
| 235 | } |
| 236 | if err := p.broker.authorityLocked(p.ctx); err != nil { |
| 237 | return toolCapability{}, err |
| 238 | } |
| 239 | return p.broker.capability, nil |
| 240 | }, func(q toolRequest) (any, error) { |
| 241 | if e := p.submit(p.ctx, q.Name, q.RequestID, q.Arguments); e != nil { |
| 242 | return nil, e |
| 243 | } |
| 244 | p.broker.mu.Lock() |
| 245 | bound := p.broker.binding |
| 246 | p.broker.mu.Unlock() |
| 247 | if q.Name == "ask_person" && bound.Ask != nil { |
| 248 | answer, e := bound.Ask(p.ctx, bound, q.RequestID, q.Arguments) |
| 249 | if e != nil { |
| 250 | return nil, e |
| 251 | } |
| 252 | p.broker.mu.Lock() |
| 253 | defer p.broker.mu.Unlock() |
| 254 | if bound.Session != p.broker.binding.Session || bound.TurnID != p.broker.binding.TurnID { |
| 255 | return nil, runnerproto.ErrInvalid |
| 256 | } |
| 257 | if e = p.broker.current(p.ctx); e != nil { |
| 258 | return nil, e |
| 259 | } |
| 260 | return map[string]any{"content": []any{map[string]string{"type": "text", "text": string(answer)}}}, nil |
| 261 | } |
| 262 | return nil, nil |
| 263 | }, p.permission()) |
| 264 | }() |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | type proxyReader struct{ conn net.Conn } |
| 269 | |
| 270 | func (r *proxyReader) Read(b []byte) (int, error) { |
| 271 | return r.conn.Read(b) |
| 272 | } |
| 273 | func (p *ToolProxy) permission() func(context.Context, json.RawMessage) (json.RawMessage, error) { |
| 274 | if p.broker.binding.Permission == nil { |
| 275 | return nil |
| 276 | } |
| 277 | return func(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { |
| 278 | p.broker.mu.Lock() |
| 279 | err := p.broker.current(ctx) |
| 280 | fn := p.broker.binding.Permission |
| 281 | session, turn := p.broker.binding.Session, p.broker.binding.TurnID |
| 282 | p.broker.mu.Unlock() |
| 283 | if err != nil { |
| 284 | return nil, err |
| 285 | } |
| 286 | result, err := fn(ctx, raw) |
| 287 | if err != nil { |
| 288 | return nil, err |
| 289 | } |
| 290 | p.broker.mu.Lock() |
| 291 | defer p.broker.mu.Unlock() |
| 292 | if session != p.broker.binding.Session || turn != p.broker.binding.TurnID { |
| 293 | return nil, runnerproto.ErrInvalid |
| 294 | } |
| 295 | if err = p.broker.current(ctx); err != nil { |
| 296 | return nil, err |
| 297 | } |
| 298 | return result, nil |
| 299 | } |
| 300 | } |
| 301 | func (p *ToolProxy) submit(ctx context.Context, name, id string, args json.RawMessage) error { |
| 302 | p.broker.mu.Lock() |
| 303 | b := p.broker.binding |
| 304 | cap := p.broker.capability |
| 305 | p.broker.mu.Unlock() |
| 306 | return p.broker.submit(ctx, toolRequest{Capability: cap.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: id, Name: name, Arguments: args}) |
| 307 | } |
| 308 | |
| 309 | // ValidateApproval does not execute a tool. The eventual socket call repeats |
| 310 | // every validation and uses the existing durable submission idempotency key. |
| 311 | func (p *ToolProxy) ValidateApproval(ctx context.Context, q ToolSubmission) error { |
| 312 | s := p.broker |
| 313 | s.mu.Lock() |
| 314 | defer s.mu.Unlock() |
| 315 | b := s.binding |
| 316 | if q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || q.Agent != b.Agent || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 { |
| 317 | return runnerproto.ErrInvalid |
| 318 | } |
| 319 | if err := validateToolArguments(q.Name, q.Arguments); err != nil { |
| 320 | return err |
| 321 | } |
| 322 | if err := b.Journal.toolSlot(ctx, b, q.RequestID, q.Name, q.Arguments); err != nil { |
| 323 | return err |
| 324 | } |
| 325 | if err := b.Journal.validateToolReplay(ctx, q); err != nil { |
| 326 | return err |
| 327 | } |
| 328 | return s.current(ctx) |
| 329 | } |
| 330 | |
| 331 | // authorityLocked releases the broker lock during remote validation. The caller |
| 332 | // holds the lock on entry and return; authority applies only to the same binding. |
| 333 | func (s *AttemptSocket) authorityLocked(ctx context.Context) error { |
| 334 | b := s.binding |
| 335 | s.mu.Unlock() |
| 336 | err := b.Current(ctx) |
| 337 | s.mu.Lock() |
| 338 | if err != nil { |
| 339 | s.invalidateLocked() |
| 340 | return err |
| 341 | } |
| 342 | if ctx.Err() != nil || s.invalid || !time.Now().Before(s.binding.LeaseDeadline) || s.binding.Session != b.Session || s.binding.TurnID != b.TurnID || s.binding.Agent != b.Agent { |
| 343 | return runnerproto.ErrInvalid |
| 344 | } |
| 345 | return nil |
| 346 | } |
| 347 | |
| 348 | func (s *AttemptSocket) current(ctx context.Context) error { |
| 349 | if ctx.Err() != nil || s.invalid || s.pending || !time.Now().Before(s.binding.LeaseDeadline) { |
| 350 | return runnerproto.ErrInvalid |
| 351 | } |
| 352 | b := s.binding |
| 353 | if err := s.authorityLocked(ctx); err != nil { |
| 354 | return err |
| 355 | } |
| 356 | if b.Session.AttemptKey != "" { |
| 357 | if b.Agent.AgentID != b.Session.AttemptKey || b.Agent.ProviderSessionID != b.Session.ID || b.Agent.Provider != b.Session.Provider { |
| 358 | return runnerproto.ErrInvalid |
| 359 | } |
| 360 | if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { |
| 361 | return err |
| 362 | } |
| 363 | } |
| 364 | return b.Journal.AdmissionAllowed(ctx) |
| 365 | } |
| 366 | func (j *Journal) currentDirectTurn(ctx context.Context, s provider.Session, turn string) error { |
| 367 | if s.ID == "" || s.AttemptKey == "" || turn == "" { |
| 368 | return runnerproto.ErrInvalid |
| 369 | } |
| 370 | var count int |
| 371 | if err := j.db.QueryRowContext(ctx, `SELECT count(*) FROM direct_turns t JOIN direct_attempts a ON a.attempt=t.attempt WHERE t.attempt=? AND t.session=? AND t.turn=? AND t.state='dispatched' AND a.recovered=0 AND a.session=?`, s.AttemptKey, s.ID, turn, s.ID).Scan(&count); err != nil { |
| 372 | return err |
| 373 | } |
| 374 | if count != 1 { |
| 375 | return runnerproto.ErrInvalid |
| 376 | } |
| 377 | var raw []byte |
| 378 | var launch provider.Launch |
| 379 | if err := j.db.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE attempt=?", s.AttemptKey).Scan(&raw); err != nil { |
| 380 | return err |
| 381 | } |
| 382 | if json.Unmarshal(raw, &launch) != nil || s.Validate(launch) != nil { |
| 383 | return runnerproto.ErrInvalid |
| 384 | } |
| 385 | return nil |
| 386 | } |
| 387 | |