package runner import ( "context" "crypto/rand" "encoding/json" "fmt" "net" "os" "path/filepath" "slices" "sync" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) const directMCP = `{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}` // ToolProxy exposes MCP only. The authenticating broker and its capability stay // in the runner; neither is written into the mounted endpoint directory. type ToolProxy struct { coordinator *coordinatorBroker SocketPath string broker *AttemptSocket listener *net.UnixListener ctx context.Context cancel context.CancelFunc workers sync.WaitGroup once sync.Once directory string } func OpenToolProxy(ctx context.Context, b ToolBinding) (*ToolProxy, error) { if b.Journal == nil { return nil, runnerproto.ErrInvalid } return openToolProxy(ctx, b, filepath.Dir(b.Journal.path)) } func openToolProxy(ctx context.Context, b ToolBinding, root string) (*ToolProxy, error) { 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) { return nil, runnerproto.ErrInvalid } for _, name := range b.Tools { if !slices.Contains([]string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction", "submit_acceptance", "submit_answer", "submit_render"}, name) { return nil, runnerproto.ErrInvalid } } if err := b.Current(ctx); err != nil { return nil, err } parent, err := openPrivateDir(root) if err != nil { return nil, err } parent.Close() dir, err := os.MkdirTemp(root, "tool-") if err != nil { return nil, err } ok := false defer func() { if !ok { os.Remove(filepath.Join(dir, "equipo.sock")) os.Remove(dir) } }() fd, err := openPrivateDir(dir) if err != nil { return nil, err } defer fd.Close() path := filepath.Join(dir, "equipo.sock") listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd()), Net: "unix"}) if err != nil { return nil, err } listener.SetUnlinkOnClose(false) if err = os.Chmod(path, 0600); err != nil { listener.Close() return nil, err } ctx, cancel := context.WithCancel(ctx) b.Tools = slices.Clone(b.Tools) 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}} p := &ToolProxy{SocketPath: path, broker: broker, listener: listener, ctx: ctx, cancel: cancel, directory: dir} p.workers.Add(2) go p.accept() // Cancellation closes all connections and permanently invalidates the broker. context.AfterFunc(ctx, func() { _ = p.Close() }) go func() { defer p.workers.Done() tick := time.NewTicker(100 * time.Millisecond) defer tick.Stop() for { select { case <-ctx.Done(): return case <-tick.C: broker.mu.Lock() b := broker.binding var err error if broker.invalid || !time.Now().Before(b.LeaseDeadline) { err = runnerproto.ErrInvalid } if err == nil && b.Session.AttemptKey != "" { var recovered int err = b.Journal.db.QueryRowContext(ctx, "SELECT recovered FROM direct_attempts WHERE attempt=?", b.Session.AttemptKey).Scan(&recovered) if recovered != 0 { err = runnerproto.ErrInvalid } } broker.mu.Unlock() if err != nil { cancel() return } } } }() ok = true return p, nil } // BindTurn is called by the trusted supervisor after session identity and turn // identity is durable, before StartTurn writes its prompt. Calls still require // durable dispatch. Binding never changes the task, fence or tools. func (p *ToolProxy) BindTurn(session provider.Session, turn string) error { if p.coordinator != nil { return p.bindCoordinator(session, turn) } s := p.broker s.mu.Lock() defer s.mu.Unlock() if s.invalid || p.ctx.Err() != nil || s.binding.Agent.Provider != session.Provider { return runnerproto.ErrInvalid } if s.binding.Session.AttemptKey != "" && s.binding.Session != session { return runnerproto.ErrInvalid } if err := s.authorityLocked(p.ctx); err != nil { return err } var saved string var recovered int if turn == "" { return runnerproto.ErrInvalid } 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 { return runnerproto.ErrInvalid } if s.binding.TurnID != "" && s.binding.TurnID != turn { var active int 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 { return runnerproto.ErrInvalid } } s.binding.Session = session s.binding.TurnID = turn s.binding.Agent.AgentID = session.AttemptKey s.binding.Agent.ProviderSessionID = session.ID s.pending = false return nil } // RenewLease accepts only the supervisor's trusted monotonic renewal. func (p *ToolProxy) RenewLease(ctx context.Context, deadline time.Time) error { if p.coordinator != nil { b := p.coordinator if err := b.current(ctx, false); err != nil { return err } b.mu.Lock() defer b.mu.Unlock() if !deadline.After(b.deadline) || deadline.After(b.binding.Claim.AttemptDeadline) { return runnerproto.ErrInvalid } b.deadline = deadline return nil } return p.broker.RenewLease(ctx, deadline) } func (p *ToolProxy) MCP() json.RawMessage { return json.RawMessage(directMCP) } func (p *ToolProxy) Close() error { p.once.Do(func() { p.cancel() if p.broker != nil { p.broker.Invalidate() } if p.coordinator != nil { p.coordinator.mu.Lock() p.coordinator.invalid = true p.coordinator.mu.Unlock() } p.listener.Close() }) p.workers.Wait() if err := os.Remove(p.SocketPath); err != nil && !os.IsNotExist(err) { return err } if err := os.Remove(p.directory); err != nil && !os.IsNotExist(err) { return err } return nil } func (p *ToolProxy) accept() { defer p.workers.Done() for { conn, err := p.listener.AcceptUnix() if err != nil { return } p.workers.Add(1) go func() { defer p.workers.Done() defer conn.Close() stop := context.AfterFunc(p.ctx, func() { conn.Close() }) defer stop() if !toolPeer(conn) { return } if p.coordinator != nil { p.serveCoordinator(conn) return } // Cancellation and lease loss close idle connections through AfterFunc. input := &proxyReader{conn: conn} _ = serveTools(p.ctx, input, conn, func() (toolCapability, error) { p.broker.mu.Lock() defer p.broker.mu.Unlock() if p.broker.invalid || p.ctx.Err() != nil { return toolCapability{}, runnerproto.ErrInvalid } if err := p.broker.authorityLocked(p.ctx); err != nil { return toolCapability{}, err } return p.broker.capability, nil }, func(q toolRequest) (any, error) { if e := p.submit(p.ctx, q.Name, q.RequestID, q.Arguments); e != nil { return nil, e } p.broker.mu.Lock() bound := p.broker.binding p.broker.mu.Unlock() if q.Name == "ask_person" && bound.Ask != nil { answer, e := bound.Ask(p.ctx, bound, q.RequestID, q.Arguments) if e != nil { return nil, e } p.broker.mu.Lock() defer p.broker.mu.Unlock() if bound.Session != p.broker.binding.Session || bound.TurnID != p.broker.binding.TurnID { return nil, runnerproto.ErrInvalid } if e = p.broker.current(p.ctx); e != nil { return nil, e } return map[string]any{"content": []any{map[string]string{"type": "text", "text": string(answer)}}}, nil } return nil, nil }, p.permission()) }() } } type proxyReader struct{ conn net.Conn } func (r *proxyReader) Read(b []byte) (int, error) { return r.conn.Read(b) } func (p *ToolProxy) permission() func(context.Context, json.RawMessage) (json.RawMessage, error) { if p.broker.binding.Permission == nil { return nil } return func(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { p.broker.mu.Lock() err := p.broker.current(ctx) fn := p.broker.binding.Permission session, turn := p.broker.binding.Session, p.broker.binding.TurnID p.broker.mu.Unlock() if err != nil { return nil, err } result, err := fn(ctx, raw) if err != nil { return nil, err } p.broker.mu.Lock() defer p.broker.mu.Unlock() if session != p.broker.binding.Session || turn != p.broker.binding.TurnID { return nil, runnerproto.ErrInvalid } if err = p.broker.current(ctx); err != nil { return nil, err } return result, nil } } func (p *ToolProxy) submit(ctx context.Context, name, id string, args json.RawMessage) error { p.broker.mu.Lock() b := p.broker.binding cap := p.broker.capability p.broker.mu.Unlock() 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}) } // ValidateApproval does not execute a tool. The eventual socket call repeats // every validation and uses the existing durable submission idempotency key. func (p *ToolProxy) ValidateApproval(ctx context.Context, q ToolSubmission) error { s := p.broker s.mu.Lock() defer s.mu.Unlock() b := s.binding 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 { return runnerproto.ErrInvalid } if err := validateToolArguments(q.Name, q.Arguments); err != nil { return err } if err := b.Journal.toolSlot(ctx, b, q.RequestID, q.Name, q.Arguments); err != nil { return err } if err := b.Journal.validateToolReplay(ctx, q); err != nil { return err } return s.current(ctx) } // authorityLocked releases the broker lock during remote validation. The caller // holds the lock on entry and return; authority applies only to the same binding. func (s *AttemptSocket) authorityLocked(ctx context.Context) error { b := s.binding s.mu.Unlock() err := b.Current(ctx) s.mu.Lock() if err != nil { s.invalidateLocked() return err } 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 { return runnerproto.ErrInvalid } return nil } func (s *AttemptSocket) current(ctx context.Context) error { if ctx.Err() != nil || s.invalid || s.pending || !time.Now().Before(s.binding.LeaseDeadline) { return runnerproto.ErrInvalid } b := s.binding if err := s.authorityLocked(ctx); err != nil { return err } if b.Session.AttemptKey != "" { if b.Agent.AgentID != b.Session.AttemptKey || b.Agent.ProviderSessionID != b.Session.ID || b.Agent.Provider != b.Session.Provider { return runnerproto.ErrInvalid } if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { return err } } return b.Journal.AdmissionAllowed(ctx) } func (j *Journal) currentDirectTurn(ctx context.Context, s provider.Session, turn string) error { if s.ID == "" || s.AttemptKey == "" || turn == "" { return runnerproto.ErrInvalid } var count int 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 { return err } if count != 1 { return runnerproto.ErrInvalid } var raw []byte var launch provider.Launch if err := j.db.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE attempt=?", s.AttemptKey).Scan(&raw); err != nil { return err } if json.Unmarshal(raw, &launch) != nil || s.Validate(launch) != nil { return runnerproto.ErrInvalid } return nil }