package runner import ( "bytes" "context" "encoding/json" "fmt" "net" "os" "path/filepath" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/coordinator" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/codex" "amadan.net/oficina/equipo/internal/runnerproto" ) type CoordinatorToolBinding struct { Claim runnerproto.CoordinatorClaim Session provider.Session Journal *Journal Current func(context.Context) error Call func(context.Context, runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) } type coordinatorBroker struct { mu sync.Mutex binding CoordinatorToolBinding invalid bool deadline time.Time } func OpenCoordinatorToolProxy(ctx context.Context, b CoordinatorToolBinding) (*ToolProxy, error) { c := b.Claim if b.Journal == nil || b.Current == nil || b.Call == nil || c.Binding.ID == "" || c.Binding.Generation < 1 || c.Turn.ID == "" || c.Turn.Generation != c.Binding.Generation || c.Scope.Account == "" || c.Handle.Attempt <= 0 || c.Handle.Fence <= 0 || c.Brief.Target.Repository != "" || c.Brief.Selection.Isolation.Status != "confined" || !time.Now().Before(c.LeaseDeadline) || !time.Now().Before(c.AttemptDeadline) { return nil, runnerproto.ErrInvalid } if err := b.Current(ctx); err != nil { return nil, err } root := filepath.Dir(b.Journal.path) parent, err := openPrivateDir(root) if err != nil { return nil, err } parent.Close() dir, err := os.MkdirTemp(root, "coordinator-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) p := &ToolProxy{SocketPath: path, listener: listener, ctx: ctx, cancel: cancel, directory: dir, coordinator: &coordinatorBroker{binding: b, deadline: c.LeaseDeadline}} p.workers.Add(1) go p.accept() context.AfterFunc(ctx, func() { _ = p.Close() }) p.workers.Add(1) go func() { defer p.workers.Done() tick := time.NewTicker(100 * time.Millisecond) defer tick.Stop() for { select { case <-ctx.Done(): return case <-tick.C: if err := p.coordinator.check(ctx, false, false); err != nil { cancel() return } } } }() ok = true return p, nil } func (b *coordinatorBroker) current(ctx context.Context, dispatched bool) error { return b.check(ctx, dispatched, true) } // The local watchdog checks deadlines without renewing remote authority. Actual // tool use rechecks authority, and the service renews at the lease cadence. func (b *coordinatorBroker) check(ctx context.Context, dispatched, remote bool) error { b.mu.Lock() v, invalid, deadline := b.binding, b.invalid, b.deadline b.mu.Unlock() if invalid || ctx.Err() != nil || !time.Now().Before(deadline) || !time.Now().Before(v.Claim.AttemptDeadline) { return runnerproto.ErrInvalid } if remote { if err := v.Current(ctx); err != nil { b.mu.Lock() b.invalid = true b.mu.Unlock() return err } } if v.Session.ID != "" { if v.Session.Provider != v.Claim.Brief.Selection.Provider || v.Session.AccountID != v.Claim.Brief.Selection.AccountID || v.Session.Model != v.Claim.Brief.Selection.Model { return runnerproto.ErrInvalid } if dispatched { if err := v.Journal.currentDirectTurn(ctx, v.Session, v.Claim.Turn.ID); err != nil { return err } } } else if dispatched { return runnerproto.ErrInvalid } return v.Journal.AdmissionAllowed(ctx) } func (p *ToolProxy) bindCoordinator(session provider.Session, turn string) error { b := p.coordinator if err := b.current(p.ctx, false); err != nil { return err } b.mu.Lock() defer b.mu.Unlock() if turn != b.binding.Claim.Turn.ID || session.ID == "" || session.AttemptKey == "" || session.Provider != b.binding.Claim.Brief.Selection.Provider || session.AccountID != b.binding.Claim.Brief.Selection.AccountID || session.Model != b.binding.Claim.Brief.Selection.Model || (b.binding.Session.ID != "" && b.binding.Session != session) { return runnerproto.ErrInvalid } var saved string var recovered int if err := b.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 } b.binding.Session = session return nil } func (p *ToolProxy) ValidateCoordinatorApproval(ctx context.Context, call runnerproto.CoordinatorToolCall) error { b := p.coordinator if b == nil { return runnerproto.ErrInvalid } if err := b.current(ctx, true); err != nil { return err } b.mu.Lock() v := b.binding b.mu.Unlock() return v.Journal.reserveCoordinatorTool(ctx, v.Claim, v.Session, call) } func (p *ToolProxy) CallCoordinatorTool(ctx context.Context, call runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) { var zero runnerproto.CoordinatorToolResult if err := p.ValidateCoordinatorApproval(ctx, call); err != nil { return zero, err } b := p.coordinator b.mu.Lock() v := b.binding b.mu.Unlock() if err := v.Journal.submitCoordinatorTool(ctx, v.Claim, v.Session, call); err != nil { return zero, err } // Always revisit instance authority, including acknowledged local replays. out, err := v.Call(ctx, call) if err != nil { return zero, err } if err = b.current(ctx, true); err != nil { return zero, err } if err = v.Journal.ackCoordinatorTool(ctx, v.Claim, v.Session, call, out); err != nil { return zero, err } return out, nil } func coordinatorMCPCall(name string, raw json.RawMessage) (runnerproto.CoordinatorToolCall, error) { var fields map[string]json.RawMessage if runnerproto.DecodeLimit(bytes.NewReader(raw), &fields, maxToolFrame) != nil { return runnerproto.CoordinatorToolCall{}, runnerproto.ErrInvalid } var id string if json.Unmarshal(fields["request_id"], &id) != nil { return runnerproto.CoordinatorToolCall{}, runnerproto.ErrInvalid } delete(fields, "request_id") args, err := json.Marshal(fields) call := runnerproto.CoordinatorToolCall{RequestID: id, Name: name, Arguments: args} if err != nil { return call, err } return coordinator.Canonical(call) } func (p *ToolProxy) coordinatorPermission(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { var q struct { Tool string `json:"tool_name"` UseID string `json:"tool_use_id,omitempty"` Input json.RawMessage `json:"input"` } if runnerproto.DecodeLimit(bytes.NewReader(raw), &q, maxToolFrame) != nil || !strings.HasPrefix(q.Tool, "mcp__equipo__") { return nil, runnerproto.ErrInvalid } call, err := coordinatorMCPCall(strings.TrimPrefix(q.Tool, "mcp__equipo__"), q.Input) if err != nil { return nil, err } if err = p.ValidateCoordinatorApproval(ctx, call); err != nil { return nil, err } return json.RawMessage(`{"behavior":"allow"}`), nil } // ApproveCoordinator binds Codex's captured MCP request to the same durable hash // as execution. Native and uncorrelated requests are always denied. func (p *ToolProxy) ApproveCoordinator(ctx context.Context, l provider.Launcher, ev provider.Event) error { if p.coordinator == nil || l == nil { return runnerproto.ErrInvalid } p.coordinator.mu.Lock() b := p.coordinator.binding p.coordinator.mu.Unlock() authorize := func(ctx context.Context, original provider.Event) error { if original.SessionID != b.Session.ID || original.TurnID != b.Claim.Turn.ID || original.RequestID != ev.RequestID || !bytes.Equal(original.Payload, ev.Payload) || !bytes.Equal(original.ToolCall, ev.ToolCall) { return runnerproto.ErrInvalid } name, raw, err := codex.MCPApproval(original) if err != nil { return err } call, err := coordinatorMCPCall(name, raw) if err != nil { return err } return p.ValidateCoordinatorApproval(ctx, call) } behavior := "allow" if err := authorize(ctx, ev); err != nil { behavior = "deny" } return l.Respond(ctx, b.Session, provider.Answer{RequestID: ev.RequestID, TurnID: b.Claim.Turn.ID, Behavior: behavior, Authorize: authorize}) } func (p *ToolProxy) serveCoordinator(conn net.Conn) { b := p.coordinator b.mu.Lock() claim := b.binding.Claim b.mu.Unlock() copy := ToolCopy{Accepted: claim.ToolCopy.Accepted, Rejected: claim.ToolCopy.Rejected, Coordinator: claim.ToolCopy.Descriptions} cap := toolCapability{Coordinator: true, Copy: copy, Tools: coordinator.Names()} var permission func(context.Context, json.RawMessage) (json.RawMessage, error) if claim.Brief.Selection.Provider == "claude" { permission = p.coordinatorPermission } _ = serveTools(p.ctx, &proxyReader{conn: conn}, conn, func() (toolCapability, error) { return cap, b.current(p.ctx, false) }, func(q toolRequest) (any, error) { out, err := p.CallCoordinatorTool(p.ctx, runnerproto.CoordinatorToolCall{RequestID: q.RequestID, Name: q.Name, Arguments: q.Arguments}) if err != nil { return nil, err } raw, err := json.Marshal(out) return map[string]any{"content": []any{map[string]string{"type": "text", "text": string(raw)}}}, err }, permission) }